我有一个挑战,我需要调用许多http请求并处理它们中的每一个。 怎么做,我不想等待从其中一个获得响应,然后调用next,如何为进程响应分配一个方法(如回调)。 如何定义回调并分配给每个回调?
答案 0 :(得分:1)
您需要的是异步编程模型,您可以在其中创建异步任务, 以后 使用等待关键字响应。
基本上你不是在等待第一次异步调用完成,你只需要发出任意数量的异步任务,只有在需要响应才能继续执行程序逻辑时才能获得响应。 / p>
详细了解以下内容: https://msdn.microsoft.com/en-us/library/hh696703.aspx
答案 1 :(得分:0)
1)你可以称之为normaly(noneasync):
public string TestNoneAsync()
{
var webClient = new WebClient();
return webClient.DownloadString("http://www.google.com");
}
2)你可以使用APM(异步):
private void SpecAPI()
{
var req = (HttpWebRequest)WebRequest.Create("http://www.google.com");
//req.Method = "HEAD";
req.BeginGetResponse(
asyncResult =>
{
var resp = (HttpWebResponse)req.EndGetResponse(asyncResult);
var headersText = formatHeaders(resp.Headers);
Console.WriteLine(headersText);
}, null);
}
private string formatHeaders(WebHeaderCollection headers)
{
var headerString = headers.Keys.Cast<string>()
.Select(header => string.Format("{0}:{1}", header, headers[header]));
return string.Join(Environment.NewLine, headerString.ToArray());
}
3)你可以创建一个回调并将其设置为EAP。(异步.net 2):
public void EAPAsync()
{
var webClient = new WebClient();
webClient.DownloadStringAsync(new Uri("http://www.google.com"));
webClient.DownloadStringCompleted += webClientDownloadStringCompleted;
}
void webClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
// use e.Result
Console.WriteLine("download completed callback.");
}
4)你可以使用更新的方式TAP,清除方式(c#5)。它的推荐:
public async Task<string> DownloadAsync(string url)
{
var webClient = new WebClient();
return await webClient.DownloadStringTaskAsync(url);
}
public void DownloadAsyncHandler()
{
//DownloadAsync("http://www.google.com");
}
此解决方案中的线程是不错的approch。(许多线程等待调用http请求!)