Question

I am refereing to this blog that explains usage of await and async keyword in .Net framework 4.5

I am trying to address following realtime scenario using these keywords

I have two devices Device1 and Device2. These devices are connected to my computer using Serial port ( RS 232 ). I have a windows application to which is capable of sending commands to these devices.
Now, initially I have to start these two devices by sending specific RS-232 commands. Now I can do this job simultaneously and update the UI accordingly. Below is code to solve this scenario

public class Device1 
{
    public async Task<int> Start(int sec)
    {
        Console.WriteLine("Device1 started @ : " + DateTime.Now.ToString());
        Task t = new Task(() => { Thread.Sleep(sec * 1000); });
        t.Start();
        await t;
        Console.WriteLine("Device1 finished @ : " + DateTime.Now.ToString());
        return 1;
    }         
}

public class Device2 
{
    public async Task<int> Start(int sec)
    {
        Console.WriteLine("Device2 started @ : " + DateTime.Now.ToString());
        Task t = new Task(() => { Thread.Sleep(sec * 1000); });
        t.Start();
        await t;
        Console.WriteLine("Device2 finished @ : " + DateTime.Now.ToString());
        return 1;
    }       
}

private async void button1_Click(object sender, EventArgs e)
    {
        Device2 d2= new Device2();
        Device1 d1= new Device1();

        await d2.Start(10);
        label1.Text = "d2 Started....";///It takes 10 sec to update this
        await d1.Start(5);///this line starts executing after 10 secs?  Why?
        label1.Text = "d1 Started...";

        MessageBox.Show("I am done...");///Get this message after 15 sec!!!
    }

Now my understanding was both await d2.Start(10); and await d1.Start(5); will run simultaneously and will update UI accordingly. But thats not the case. Having close look at Console.WriteLine statememts prove that its completely seqential call.
Can someone throw more light on this?

Was it helpful?

Solution

I recommend my async intro for async newbies; it has links at the end to the best followup documentation.

In short, what's happening is that you are awaiting the tasks. This will pause the method until those tasks complete. If you want to let them run concurrently, then you can save the tasks into variables (t1, t2) and then await them both (await Task.WhenAll(t1, t2);).

P.S. don't use the Task constructor or Task.Start in async code; use Task.Run instead.

OTHER TIPS

The await keyword does not make the awaited tasks (the results of d2.Start(10) and d1.Start(5), respectively) run in parallel. What it does is saying to the compiler "let the rest of this method run after the awaited tasks finishes" without blocking the thread.

You may want to read some introduction on the async/await keywords, e.g. here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top