-1

我有这个方法

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 行停止执行。

4

1 回答 1

3

您需要将 Search 从 async void 更改为 async Task 然后 Wait() 结果在 Main - 否则,它会在任务开始后退出,但没有任何东西在等待它完成。

于 2013-04-08T23:13:18.447 回答