Search code examples
c#multithreadingtaskthreadpool

What to deal with multiple asynchronous method invocations in C#


Suppose, I have a simple class, with async method in it:

public class Writer
{
    public Task WriteAsync(string message);
}

This is internal class, which is absolutely negligible for application's business logic.

The main idea of the method, is that when it's called - method must immediately returns control to the calling method, to avoid any possible delay in important, full of business logic calling method (delay for calling that method is possible of course).

This method calls in different places, very often. and we don't really care if it's successful or won't write last messages in case of unexpectable situation. That's fine.

So, the question is, how can I call WriteAsync to avoid any possible delays in calling method?

I thought about Task.Run(() => WriteAsync(message)) (without await! we don't need to wait this!), but won't that fill my thread pool with a lot of useless work? And it's quite onerously writing everywhere such code...


Solution

  • You may queue the writes and process the queue, i.e. perform the writing, on a dedicated background thread. This is kind of what happens when you call Task.Run, i.e. you queue up delegates in the thread pool. If you require more control, you may for example use a BlockingCollection<T>.

    There is an example of how to use a BlockingCollection<T> to read and write items concurrently available on MSDN.

    Using this approach, calling WriteAsync will only block for the time it takes to add the message to the queue and this time should be negligible.