如何修改不在同一线程中的对象
我正在处理异步网络请求。并且需要依赖于响应来执行消息返回。
正在考虑做某事,比如遵循
// 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;
最好的方法是什么?
I am working on a async web request. and need to depends on the response to do a message return.
was thinking to do sth like following
// 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;
what is the best way to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你是对的,该变量将始终为空,因为你使用
BeginGetResponse
方法触发了异步请求。所以你实际上有几个选择。您可以阻塞执行线程,直到响应返回(这可能是一个非常糟糕的主意,除非您有一个非常有力的论据来执行此操作),或者您可以使用基于事件的异步模式在响应返回时提醒调用者...考虑您的一些代码包装在一个方法中,
以便在此处连接基于事件的模式。我们定义一个自定义
EventArgs
类和一个自定义事件,调用者可以监听这些事件,并在响应返回时触发该事件。You are right, that variable will always be empty because you fired off an asyncronous request with the
BeginGetResponse
method. So really you have a few options here. You can either block the executing thread until the response comes back (probably a really bad idea unless you have a very strong argument for doing this), or you could use an event based asynchronous pattern to alert callers when your response returns...Consider some of your code wrapped in a method
To wire up an event based pattern here. We define a custom
EventArgs
class and a custom event which callers can listen for and which we will fire when the response comes back.