我正在处理异步Web请求。并且需要依赖于回复消息的响应。
正在考虑做下面的事情
// creating request
string messageToReturn = string.empty;
request.BeginGetResponse(ar =>
{
HttpWebRequest req2 = (HttpWebRequest)ar.AsyncState;
var response = (HttpWebResponse)req2.EndGetResponse(ar);
// is it safe to do this?
messageToReturn = "base on respone, assign different message";
}, request);
// will i get any response message? i will always get empty right?
// since response is handle in another thread
return messageToReturn;
最好的方法是什么?
答案 0 :(得分:0)
您是对的,因为您使用BeginGetResponse
方法触发了异步请求,因此该变量将始终为空。所以你真的有几个选择。您可以阻止正在执行的线程,直到响应返回(可能是一个非常糟糕的主意,除非您有一个非常强大的参数来执行此操作),或者您可以使用基于事件的异步模式在响应返回时提醒呼叫者... < / p>
考虑一些包含在方法中的代码
public void GetMessageAsync()
{
string messageToReturn = string.empty;
request.BeginGetResponse(ar =>
{
HttpWebRequest req2 = (HttpWebRequest)ar.AsyncState;
var response = (HttpWebResponse)req2.EndGetResponse(ar);
// is it safe to do this?
messageToReturn = "base on respone, assign different message";
}, request);
}
在此处连接基于事件的模式。我们定义了一个自定义EventArgs
类和一个自定义事件,调用者可以监听这些事件,并在响应回来时触发。
public class StringEventArgs : EventArgs
{
public string Message { get; set; }
}
public event EventHandler<StringEventArgs> MessageReturned;
public void GetMessageAsync()
{
//string messageToReturn = string.empty;
request.BeginGetResponse(ar =>
{
HttpWebRequest req2 = (HttpWebRequest)ar.AsyncState;
var response = (HttpWebResponse)req2.EndGetResponse(ar);
//messageToReturn = "base on respone, assign different message";
this.MessageReturned(this, new StringEventArgs { Message = response.ToString() });
}, request);
}