私はこの方法を持っています
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 行で実行を停止します。