Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an await statement for threads?

Hi I would like to know if there is something similiar to the await statement, which is used with tasks, which I can implement with threads in c#?

What I want to do is:

Start Thread A, compute some data and put the result on variable x. After that variable x is transferred to another thread B and at the same time Thread A starts again to compute some data, while thread B starts another calculation with the result x.

UPDATE: Ok there seems to be some confusion so I will be more accurate in my description:

I use two sensors which produce data. The data needs to be retrieved in such a way that SensorA data is retrieved (which takes a long time) and immediately after that the data from SensorB must be retrieved in another Thread, while SensorA continues retrieving another data block. The problem is i cant queue the data of both sensors in the same queue, but I need to store the data of both sensor in ONE data structure/object.

My idea was like that:

  1. Get Data from Sensor A in Thread A.
  2. Give result to Thread B and restart Thread A.
  3. While Thread A runs again Thread B gets Data from Sensor B and computes the data from Sensor A and B

You can assume that Thread A always needs a longer time than Thread B

like image 963
DerBenutzer Avatar asked Jan 15 '16 09:01

DerBenutzer


1 Answers

As I said in a comment. This looks like classic Producer/Consumer, for which we can use e.g. a BlockingCollection.

This is a slight modification of the sample from that page:

BlockingCollection<Data> dataItems = new BlockingCollection<Data>(100);

// "Thread B"
Task.Run(() => 
{
    while (!dataItems.IsCompleted)
    {
        Data dataA = null;
        try
        {
            dataA = dataItems.Take();
        }
        catch (InvalidOperationException) { }

        if (dataA != null)
        {
            var dataB = ReadSensorB();
            Process(dataA,dataB);
        }
    }
    Console.WriteLine("\r\nNo more items to take.");
});

// "Thread A"
Task.Run(() =>
{
    while (moreItemsToAdd)
    {
        Data dataA = ReadSensorA();
        dataItems.Add(dataA);
    }
    // Let consumer know we are done.
    dataItems.CompleteAdding();
});

And then moreItemsToAdd is just whatever code you need to have to cope with needing to shut this process down.

like image 67
Damien_The_Unbeliever Avatar answered Sep 30 '22 06:09

Damien_The_Unbeliever