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 (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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With