Вы должны указать BeginGetResponse
, чтобы вернуться в тот же контекст, в котором он был вызван через SynchronizationContext.Current
.Примерно так (код не имеет надлежащей проверки ошибок, поэтому вы должны правильно об этом подумать) (Кроме того, Platinum Azure правильно, что вы должны использовать using
, чтобы ваши потоки закрывались правильно (и гарантировано):
В вашем SendLoginRequest:
//Box your object state with the current thread context
object[] boxedItems = new []{request, SynchronizationContext.Current};
request.BeginGetResponse(new AsyncCallback(GetLoginResponseCallback),
boxedItems);
Код getresponse:
private static void GetLoginResponseCallback(IAsyncResult asynchronousResult)
{
//MY UPDATE
//Unbox your object state with the current thread context
object[] boxedItems = asynchronousResult.AsyncState as object[];
HttpWebRequest request = boxedItems[0] as HttpWebRequest;
SynchronizationContext context = boxedItems[1] as SynchronizationContext;
// End the operation
using(HttpWebResponse response =
(HttpWebResponse)request.EndGetResponse(asynchronousResult))
{
using(Stream streamResponse = response.GetResponseStream())
{
using(StreamReader streamRead = new StreamReader(streamResponse))
{
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
//MY UPDATE
//Make an asynchronous call back onto the main UI thread
//(context.Send for a synchronous call)
//Pass responseString as your method parameter
//If you have more than one object, you will have to box again
context.Post(UIMethodToCall, responseString);
}
}
}
}
Для реализации обработки вашего пользовательского интерфейса
public static void UIMethodCall(object ObjectState)
{
String response = ObjectState as String;
label1.Text = String.Format("Output: {0}", response);
//Or whatever you need to do in the UI...
}
Теперь я бы протестировал этоВо-первых, я понял, что Microsoft реализовала асинхронность, управляемую событиями, что ответ был контекстно-зависимым и знал, к какому контексту возвращаться.попытка обновить пользовательский интерфейс (это вызовет исключение контекста потока, если вы не находитесь в вызывающем потоке (UI))