Silverlight async api causes freeze and no response

This code causes Silverlight to freeze. If I remove the ManualResetEvent code nothing will happen

        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();
    }
+3
source share
2 answers

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

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

, "mre.Set()" . , , , -, OpenReadAsync . , , .

+2

, , , . , , , , ReadCompleted .

: -

string dummy = "Some value"; // local value you still need to access when download complete

WebClient wc = new WebClient();
wc.OpenReadCompleted += (s, args)
{
   if (!args.Cancelled)
   {
     try
     {
         Stream stream = args.Stream;  // This is the data you are after
         // Do stuff with stream, note the dummy variable is still accessible here.
     }
     catch (Exception err)
     {
         //Do something sensible with the exception to make sure its surfaced
     }
   }
};
sender.OpenReadAsync(new Uri(this.url+"?blob="+BODY, UriKind.Relative));
0

Source: https://habr.com/ru/post/1731233/


All Articles