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?
You are right, that variable will always be empty because you fired off an asyncronous request with the
BeginGetResponsemethod. 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
EventArgsclass and a custom event which callers can listen for and which we will fire when the response comes back.