Search code examples
c#events.net-corechannelsystem.threading.channels

Wait async for a event from a never ending Task


Currently I'am build a webserver that needs to wait from incoming messages, but i need to wait asynchronisally for these messages. These messages are received in an other Task that keeps running. The endless task pushes Events and the other Task needs to wait for one of these events too be received.

If will make a sketch if needed to visualize the problem better

I have seen the TaskCompletionSource class but the task will not complete except when the client disconnects so that's not going to work. Await for the task is exactly the same.

Is there a Library or build in solution for C#/.net core?

Thank you :)


Solution

  • There is the new Channel<T> API in .NET Core 2.1 and System.Threading.Channels that lets you consume a queue asynchronously:

    Channel<int> channel = Channel.CreateUnbounded<int>();
    ...
    ChannelReader<int> c = channel.Reader;
    while (await c.WaitToReadAsync())
    {
        if (await c.ReadAsync(out int item))
        {
             // process item...
        }
    }
    

    Please refer to this blog post for an introduction and more examples of how to use it.