Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I not await for async Task without making it async void?

When using async Task method it is required to place await before method. I need code to be executed in non UI blocking manner and don't want to await. My only idea is to use:

private void TaskFactory()
{ 
    CancellationTokenSource token_TaskFactory = new CancellationTokenSource();
    ParallelOptions parOpts = new ParallelOptions();
    parOpts.CancellationToken = token_TaskFactory.Token;
    parOpts.MaxDegreeOfParallelism = Environment.ProcessorCount;
    TaskCreationOptions atp = new TaskCreationOptions();     
    atp = TaskCreationOptions.PreferFairness;
    Task TaskFactory = Task.Factory.StartNew(() => 
    {
       if (!token_TaskFactory.IsCancellationRequested)     
       {
         Thread.Sleep(5000);
       }
       else
       {

       }
    }, token_TaskFactory.Token, atp, TaskScheduler.Default); 
}
like image 432
as74 Avatar asked Feb 15 '23 21:02

as74


1 Answers

When using async Task method it is required to place await before method.

The correct way to handle this is to await the method, and make the calling method async Task or async Task<TResult>. This will have a cascading effect as async travels up through your code.

In a UI application, you will usually end up at an event handler, which cannot be async Task, and at that point you can make the event handler async void.

If you cheat this process by making a regular method async void, you cause other problems, particularly around error handling and composability (i.e. unit testing). See my MSDN article or one of the many talks about why async void should be avoided.

I need code to be executed in non UI blocking manner and don't want to await.

Why don't you "want" to use await? You have asynchronous code that you need to run in a non-blocking fashion, and that's exactly what await does!

like image 105
Stephen Cleary Avatar answered Mar 05 '23 17:03

Stephen Cleary