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:
You can assume that Thread A always needs a longer time than Thread B
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With