I'm trying to understand async await in the simplest form. I want to create a very simple method that adds two numbers for the sake of this example, granted, it's no processing time at all, it's just a matter of formulating an example here.
private async Task DoWork1Async()
{
int result = 1 + 2;
}
private async Task DoWork2Async()
{
Task.Run( () =>
{
int result = 1 + 2;
});
}
If I await DoWork1Async()
will the code run synchronously or asynchronously?
Do I need to wrap the sync code with Task.Run
to make the method awaitable AND asynchronous so as not to block the UI thread?
I'm trying to figure out if my method is a Task
or returns Task<T>
do I need to wrap the code with Task.Run
to make it asynchronous.
Stupid question I'm sure but I see examples on the net where people are awaiting code that has nothing async within and not wrapped in a Task.Run
or StartNew
.
This question is related to
c#
.net-4.5
async-await
c#-5.0
When you use Task.Run to run a method, Task gets a thread from threadpool to run that method. So from the UI thread's perspective, it is "asynchronous" as it doesn't block UI thread.This is fine for desktop application as you usually don't need many threads to take care of user interactions.
However, for web application each request is serviced by a thread-pool thread and thus the number of active requests can be increased by saving such threads. Frequently using threadpool threads to simulate async operation is not scalable for web applications.
True Async doesn't necessarily involving using a thread for I/O operations, such as file / DB access etc. You can read this to understand why I/O operation doesn't need threads. http://blog.stephencleary.com/2013/11/there-is-no-thread.html
In your simple example,it is a pure CPU-bound calculation, so using Task.Run is fine.
One of the most important thing to remember when decorating a method with async is that at least there is one await operator inside the method. In your example, I would translate it as shown below using TaskCompletionSource.
private Task<int> DoWorkAsync()
{
//create a task completion source
//the type of the result value must be the same
//as the type in the returning Task
TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
Task.Run(() =>
{
int result = 1 + 2;
//set the result to TaskCompletionSource
tcs.SetResult(result);
});
//return the Task
return tcs.Task;
}
private async void DoWork()
{
int result = await DoWorkAsync();
}
Source: Stackoverflow.com