views:

22

answers:

1

Code:

    public string GetTextWebRequest(string url)
    {
        WebClient cl = new WebClient();
        cl.DownloadStringCompleted += new DownloadStringCompletedEventHandler(cl_DownloadStringCompleted);
        cl.DownloadStringAsync(new Uri(url));
        are.WaitOne();
        return _textdata;
    }

    void cl_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        _textdata = e.Result;
        are.Set();
    }

Why am I not using the 'DownloadString' method? Because I'm using the compact framework, and async is the only option I have.

Anyway, my problem is 'DownloadStringCompleted' does not get called if the main (calling) thread is blocked. And thus never gets unblocked.

My only thoughts is that WebClient is calling 'DownloadStringCompleted' on the calling thread, which doesn't make sense?

I'm a little lost.

+1  A: 

My only thoughts is that WebClient is calling 'DownloadStringCompleted' on the calling thread, which doesn't make sense?

But that is exactly what is happening. It is badly documented but this method+event follow the backgroundworker model. You can see the relationship in the DownloadStringCompletedEventArgs members.

The Bgw pattern is used in various places in the WinForms(-related) library. See for instance the PictureBox control.

So, conclusion: don't block... You'll have to design an event-driven approach.

Henk Holterman
ahhh, i thought so. Well thanks for the confirmation.
Peanut