我有这个方法
public class WebSearcher : IWebSearcher
{
private static readonly string _rootUri;
private static readonly BingSearchContainer _bingContainer;
private static readonly string _accountKey;
static WebSearcher()
{
_rootUri = ConfigurationSettings.Settings.RootUri;
_bingContainer = new BingSearchContainer(new Uri(_rootUri));
_accountKey = ConfigurationSettings.Settings.AccountKey;
_bingContainer.Credentials = new NetworkCredential(_accountKey, _accountKey);
}
public Task<IEnumerable<WebResult>> SearchAsynch(string query)
{
if (query == null)
{
throw new ArgumentNullException("query cannot be null");
}
DataServiceQuery<WebResult> webQuery =
_bingContainer.Web(query, null, null, null, null, null, null, null);
return Task.Factory.FromAsync(webQuery.BeginExecute(null, null),
asyncResult => webQuery.EndExecute(asyncResult));
}
}
我这样称呼它
public class Client
{
public static void Main()
{
Search();
}
private static async Task Search()
{
var tasks = new Task<IEnumerable<WebResult>>[100];
IWebSearcher webSearcher = new WebSearcher();
for (var i = 0; i < 100; i++)
{
tasks[i] = webSearcher.SearchAsynch(i.ToString());
}
await Task.WhenAll(tasks);
for (var i = 0; i < 100; i++)
{
Console.WriteLine(tasks[i].Result.First().Title);
}
}
}
代码在WhenAll 行停止执行。