public string MyMethod(string param1)
{
var url = string.Format(UrlMask, HttpUtility.UrlEncode(param1), Login, ApiKey);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.BeginGetResponse(result =>
{
var requestInternal = (HttpWebRequest)result.AsyncState;
var response = (HttpWebResponse)requestInternal.EndGetResponse(result);
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
var resultXml = XDocument.Load(response.GetResponseStream());
var x = from r in resultXml.Descendants("node")
select r.Element("element").Value;
}
}, request);
return null;
}
当lambda函数完成时, MyMethod
应返回string
值。我的问题是:
request.BeginGetResponse
会完成吗? MyMethod
了解它以返回值?答案 0 :(得分:1)
要查看lambda何时完成,您可以使用如下的ManualResetEvent:
public string MyMethod(string param1)
{
const int timeOutInMs = 1000;
using (ManualResetEvent ended = new ManualResetEvent(false))
{
var url = string.Format(UrlMask, HttpUtility.UrlEncode(param1), Login, ApiKey);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.BeginGetResponse(result =>
{
var requestInternal = (HttpWebRequest) result.AsyncState;
var response = (HttpWebResponse) requestInternal.EndGetResponse(result);
using (
StreamReader streamReader =
new StreamReader(response.GetResponseStream()))
{
var resultXml = XDocument.Load(response.GetResponseStream());
var x = from r in resultXml.Descendants("node")
select r.Element("element").Value;
}
ended.Set();
}, request);
if (!ended.WaitHandle.WaitOne(timeOutInMs))
{
throw new TimeoutException("lambda took too long to complete");
}
}
return null;
}