简体   繁体   中英

C# synchronization between async tasks with infinite while loop?

I have one async task running an infinite loop doing some realtime processing:

private async void RealTimeProcessingAsync()
{
    while (true)
    {
        //....
       Tmstaus  status = await ReadStatusAsync();
       switch (status)
       {
            case Ack:
            //...
            break;
            //...
        }
        //...
    }
}

And I created another async method SendWriteRqst that post command to RealTimeProcessingAsync(), should wait for status to set to defined condition and return.

public async Task<WriteState> SendWriteRqstAsync(TmCommand tmCmd)
{
    //...
    await SomeCondition()//based on status value
    //...
    return wrState;
}

It will works if SomeCondition() runs another while loop to polling status and return true if conditions set, but I'm looking for better solution.

(Sorry for bad English)

It will works if SomeCondition() runs another while loop to polling status and return true if conditions set , but I'm looking for better solution.

What you want is a signal instead of a polling loop. If you only need to set the signal once, you can use TaskCompletionSource<T> . If you want a signal that can be set and reset (without having to be reconstructed), then you can use AsyncManualResetEvent (also available from NuGet in my AsyncEx.Coordination library ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM