Keeping The Main Thread Running with the Async CTP Dataflow


Introduction

The previous post presented some code for keeping the main thread of a console application open when the dataflow was being processed. This code I believe is down right wrong, or at least not the best way to achieve the desired result.

The wrong code

private static Task Test6_Main_Wrong()
{
    BroadcastBlock<int> bcBlock = Test6();
    for (int i = 0; i <= 100; i++)
    {
        if (bcBlock.Post(i))
            Debug.WriteLine(
                String.Format("Post of {0} Succeeded", i));
        else Debug.WriteLine(
                String.Format("Post of {0} Not Accepted", i));
    }
    bcBlock.Complete();
    while (bcBlock.Completion.IsCompleted == false)
    {
        Debug.WriteLine("Thread Sleeping");
        Thread.Sleep(1000);
    }
    Debug.WriteLine("Done");
    return bcBlock.Completion;
}

The use of the sleep is what is wrong here. It is an arbitrary value for the amount of the data flow network will take to complete.

The Right Code

private static Task Test6_Main()
{
    BroadcastBlock<int> bcBlock = Test6();
    for (int i = 0; i <= 100; i++)
    {
        if (bcBlock.Post(i))
            Debug.WriteLine(
                String.Format("Post of {0} Succeeded", i));
        else Debug.WriteLine(
                String.Format("Post of {0} Not Accepted", i));
    }
    bcBlock.Complete();
    Debug.WriteLine("Done");
    return bcBlock.Completion;
}

And the main function invocation of the function is:

Test6_Main().Wait();

Key Points:

  • Returning the Task from the function to the main. The Task Object has all the plumbing to know about competition of the task, the framework does all of the heavy lifting here.
  • The Wait method keeps the main thread open while a data flow network of any size will complete.

Conclusions

  • Using Thread.Sleep is bad in Async Dataflow applications.
  • Using Task.Wait looks like a much better way to achieve what I was after.
  • There are other occasions where I have used Sleep. I have solved one of these cases in a much better way, and I will post that example shortly.
Advertisements

, , , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: