The fact is that I came across this a little more often than never, but when I had to, I somehow did it. In general, there is one function in Silverlight.

private void button1_Click(object sender, RoutedEventArgs e) { Uri mainpage = new Uri("http://192.168.1.101:3000/"); HttpWebRequest _webrequest; _webrequest = (HttpWebRequest)HttpWebRequest.Create(mainpage); RequestState rstate = new RequestState(); rstate.request = _webrequest; try { IAsyncResult result = (IAsyncResult)_webrequest.BeginGetResponse(new AsyncCallback(RespCallback), rstate); allDone.WaitOne(); // Release the HttpWebResponse resource. rstate.response.Close(); } catch (WebException wee) { MessageBox.Show("\nException raised!\n" + "Message: " + wee.Message + "\nStatus: " + wee.Status + "\n", "Error!", MessageBoxButton.OKCancel); } catch (Exception ee) { MessageBox.Show("\nException raised!\n" + "Message: " + ee.Message + "\n", "Error!", MessageBoxButton.OKCancel); } } 

allDone.WaitOne(); waiting for the asynchronous call to complete. But at this stage, the program hangs, apparently because the error in the call. To identify them, I placed breakpoints in the RespCallback function, but for some reason the program never stops at them.

Update

I realized that the asynchronous function does not start at all, that is, it starts when the main one (which starts it) is completed. That is, only after allDone.WaitOne (); and rstate.response.Close () ;. But this does not happen because allDone.WaitOne () is waiting for a flag that is set when the RespCallback call is completed

    2 answers 2

    Transfer your code to BackgroundWorker and the problem should disappear.

      I understand, allDone.WaitOne (); blocks the current thread until the asynchronous call ends. After this, the breakpoint on the method that was called asynchronously will not work, since the method has already completed. You need to release resources in the method that you call asynchronously, and not in the caller. Now your code works in the same way as if it worked synchronously, it only consumes some of the additional resources for organizing an asynchronous call.

      • I think you did not catch the details of the problem. I edited the question to make it clearer, you re-read it and if something is wrong, then also correct your answer. If you continue to stick to your answer, then we will understand further - LackOfKnowledge