Can I not await for async Task without making it a

2019-04-10 02:03发布

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

1条回答
乱世女痞
2楼-- · 2019-04-10 02:58

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!

查看更多
登录 后发表回答