How to use async-await pattern with background task

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi, Im new to async-await pattern and Id like to get deeper understanding of asynchronous operations in 4.5 Fw. I have created small peace of code to simulate long-running asynchronous method.
<pre class="prettyprint static async Task DoSomethingAsync()
{
LogOperation("Doing something...");
Thread.Sleep(500);

LogOperation("Waiting something...");
await Task.Delay(500);

LogOperation("Doing something again...");
Thread.Sleep(500);
}

static void LogOperation(string operationName)
{
Console.WriteLine("[" + Thread.CurrentThread.ManagedThreadId + "] " + operationName);
}[/code]
The goal is to execute DoSomethingAsync() in background thread without blocking main (UI) thread and do not block any thread on waiting operation (numer 2). So it would be truly asynchronous. I have added printing of thread id on each separate operation,
so I can understand which thread is used to execute each step of async method.
Try number 1:
<pre class="prettyprint LogOperation("Start async methods.");
Task.WaitAll(DoSomethingAsync(), DoSomethingAsync());
LogOperation("Done.");[/code]
Results:<br/>
[10] Start async methods.<br/>
[10] Doing something...<br/>
[10] Waiting something...<br/>
[10] Doing something...<br/>
[10] Waiting something...<br/>
[6] Doing something again...<br/>
[12] Doing something again...<br/>
[10] Done.
Its not what I wanted, because most of code was executed on main thread.
Try 2:
<pre class="prettyprint LogOperation("Start async tasks.");
Task.WaitAll(
Task.Factory.StartNew(() => DoSomethingAsync()),
Task.Factory.StartNew(() => DoSomethingAsync()));
LogOperation("Done.");
[/code]
Results:
[10] Start async tasks.<br/>
[6] Doing something...<br/>
[12] Doing something...<br/>
[6] Waiting something...<br/>
[12] Waiting something...<br/>
[10] Done.<br/>
[6] Doing something again...<br/>
[14] Doing something again...
That is better, but seems async method is not attached to tasks I have launched via Task.Factory. So I cant wait for them, get result or catch exception (if any).
Any clues?




View the full article
 
Back
Top