Search code examples
silverlightsynchronizationwebclientsilverlight-3.0

Silverlight async api's cause hangs and none-responsiveness


this code causes silverlight to hang. If I remove the ManualResetEvent code, nothing happens

        private ManualResetEvent mre = new ManualResetEvent(false);

        ...

        WebClient sender = new WebClient();
        sender. += new OpenReadCompletedEventHandler(this.ReadComplete);
        sender.OpenReadAsync(new Uri(this.url+"?blob="+BODY, UriKind.Relative));

        mre.WaitOne();

    }
    public bool T = false;
    public void ReadComplete(object sender, OpenReadCompletedEventArgs e)
    {

        mre.Set();
    }

Solution

  • You cannot block in the UI thread (cf. "mre.WaitOne"). If you absolutely need the WaitOne, you must run your code in a separate thread. This can be done as follows:

    var t = new Thread(delegate()
    {
        //...
        mre.WaitOne();
        //...
    });
    

    One would expect that the "mre.Set()" in the callback would be triggered. However, I've had the same problem, so apparently, the OpenReadAsync callback mechanism uses the UI thread as intermediate dispatcher. That dispatching cannot happen it is waiting for the event to be set.