调用时异步方法失败

时间:2013-04-08 22:14:12

标签: c# async-await c#-5.0

我有这个方法

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

1 个答案:

答案 0 :(得分:3)

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