简体   繁体   中英

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); 
}

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 (ie 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!

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