Task.Run without wait ?

Omkar Pimplekar 1 Reputation point
2020-12-04T05:56:45.903+00:00

In .NET core 2.0 application, have requirement to run task in a background. 1 option is to use IHostedService, However can use Task.Run(() => DoSomething(a,b,c)) without wait ?
I got to know it is risky, as if any exception occurred in the background method (DoSomething), can crash application. If that can handle by Try..Catch, any other disadvantage of using Task.Run() for background method.
Thanks.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,633 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,386 Reputation points
    2020-12-04T18:37:20.577+00:00

    Hello @Omkar Pimplekar

    Here is one option using ForGet, which requires the following NuGet package.

    public static async Task<bool> SomeTask()  
    {  
        return await Task.Run(async () =>  
        {  
            await Task.Delay(2000);  
            Console.WriteLine("hello");  
            return true;  
        });  
      
    }  
    

    Usage

    Console.WriteLine("Before");  
    SomeTask().Forget();  
    Console.WriteLine("After");  
    

    Results where hello shows up after "after". Now there is a caveat, if code can fail make sure that the calling method wraps the code in a try/catch and that the calling method is not marked as void else the exception is not bubbled up to the caller.

    Before  
    After  
    hello  
    
    2 people found this answer helpful.
    0 comments No comments

  2. Collin Brittain 36 Reputation points
    2020-12-04T18:05:05.043+00:00

    You can fire and forget with Task.Run(() => DoSomething()).ConfigureAwait(false);, but use it at your own risk as you've mentioned.

    1 person found this answer helpful.
    0 comments No comments