简体   繁体   中英

Why to use Async inside Task.Run?

While working on some code, I came across the following,

Approach 1:

private void MyMethod()
{
    var t = Task.Run(
        async () =>
        {
            Foo.Fim();
            await Task.Delay(5000); 
        });
    t.Wait();
}

We deliberately introduce a delay of 5 seconds to allow Fim() to complete its work. It is required to introduce the delay - imagine this to be calling a third party API which mandates a cooling period of 5 seconds.

I wanted to understand if this the right approach to wait for an operation to complete. How is Approach 1 different from the following Approach 2? Or is there a better way to do this? All we need is to have the cooling period delay and avoid blocking the UI.

Approach 2:

private void MyMethod()
{
    var t = Task.Run(
        () =>         
        {
            Foo.Fim();
            Task.Delay(5000).Wait(); // some operation which takes 5  seconds.
        });
    t.Wait();
}

What you need is a throttler, and a handy class for implementing one is the SemaphoreSlim :

Limits the number of threads that can access a resource or pool of resources concurrently.

private SemaphoreSlim _myMethodSemaphore = new SemaphoreSlim(1);

private void MyMethod()
{
    _ = Task.Run(async () =>
    {
        await _myMethodSemaphore.WaitAsync();
        try
        {
            Foo.Fim();
        }
        finally
        {
            await Task.Delay(5000); // Impose the delay even in case of an exception
            _myMethodSemaphore.Release();
        }
    });
}

Note that there is no Wait() in this example. The only blocking call is the Foo.Fim() method call. By making this method asynchronous you could have a perfect solution regarding scalability: await Foo.FimAsync()

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