NeddySpaghetti
NeddySpaghetti

Reputation: 13495

Do event based asynchronous pattern implementation always capture the current synchronization context?

I was looking through some code in Bart De Smet's C# 5.0 Unleashed book and while playing around with it using WebClient.

In the code below, I noticed that the callback was executed on the UI thread. I know that WebClient.DownloadStringAsync implementation of EAP captures the current SynchronizationContext, and was wandering whether all implementations of EAP do this as there appears to be no way to specify what SynchronizationContext to execute the callback on.

Here is the code in question:

    private void loadButton_Click(object sender, EventArgs e)
    {
        var client = new WebClient();

        client.DownloadStringCompleted += (o, args) =>
            {
                if (args.Error != null)
                {
                    try
                    {
                        throw args.Error; // simply to restore structured exception handling?!
                    }
                    catch (WebException)
                    {
                        this.textBox.Text = "ERROR: " + args.Error.Message;
                    }

                    return;
                }

                // Already on the UI thread!
                this.textBox.Text = args.Result;
            };

        client.DownloadStringAsync(new Uri(@"http:\\www.rpmglobal.com"));
    }

Upvotes: 0

Views: 91

Answers (1)

Drew Marsh
Drew Marsh

Reputation: 33379

No, definitely not. WebClient's implementation does sniff the current SynchronizationContext when you make the call that will eventually trigger the event to notify you (e.g. DownloadStringAsync), but that's purely implementation specific and not a guarantee of EAP.

Upvotes: 1

Related Questions