Hi,@Markus Freitag . Welcome to Microsoft Q&A . You could use ConcurrentQueue<T> to safely manage a collection of data that can be accessed by multiple threads. Here's a simple example using ConcurrentQueue<T> in a WPF desktop application. This example assumes you have a button in your UI to start the producer and consumer tasks.
public partial class MainWindow : Window
{
private ConcurrentQueue<string> dataQueue = new ConcurrentQueue<string>();
private bool isRunning = true;
public MainWindow()
{
InitializeComponent();
}
private async void StartButton_Click(object sender, RoutedEventArgs e)
{
Task producer = Task.Run(() => ProducerFunction());
Task consumer = Task.Run(() => ConsumerFunction());
await Task.Delay(5000);
// Stop the tasks
isRunning = false;
// Wait for both tasks to complete
await Task.WhenAll(producer, consumer);
}
private void ProducerFunction()
{
while (isRunning)
{
// Simulate getting data (replace this with your actual data retrieval logic)
string newData = GetDataFromJsonSource();
// Add data to the queue
dataQueue.Enqueue(newData);
// Simulate some delay before getting the next data
Task.Delay(1000).Wait();
}
}
private void ConsumerFunction()
{
while (isRunning || dataQueue.Count > 0)
{
// Try to dequeue data
if (dataQueue.TryDequeue(out string data))
{
// Process the data (replace this with your actual data processing logic)
ProcessData(data);
}
else
{
// If the queue is empty, wait for a short time before checking again
Task.Delay(100).Wait();
}
}
}
private string GetDataFromJsonSource()
{
// Simulate data retrieval from a JSON source
return "{\"key\": \"value\"}";
}
private void ProcessData(string data)
{
// Simulate processing data
Console.WriteLine($"Processed data: {data}");
}
}
In this example, the ProducerFunction simulates getting data from a JSON source and adds it to the ConcurrentQueue. The ConsumerFunction continuously tries to dequeue data and process it. The isRunning flag is used to control when the tasks should stop.
The Task.Delay is used for simulating operations. In your scenario, you would replace these with actual data retrieval and processing logic. The StartButton_Click
method starts the producer and consumer tasks and allows them to run for a while before stopping them.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.