Can I not wait for async Task without async void?

When using the async Task method, a wait method must be set before the call. I need code that will execute in non-user interface lock mode and doesn't want to wait. 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); } 
+4
source share
1 answer

When using the async Task method, a wait method must be set before the call.

The proper way to handle this is with the await method and make the calling method async Task or async Task<TResult> . This will have a cascading effect, since async moves around your code.

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

If you cheat on this process using the usual async void method, you cause other problems, especially with regard to error handling and the possibility of linking (i.e. unit testing). See my MSDN article or one of the many discussions about why async void should be avoided.

I need a code that will execute in non-UI lock mode and doesn't want to wait.

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

+8
source

Source: https://habr.com/ru/post/1492235/


All Articles