简体   繁体   English

异步方法在调用时失败

[英]Async method failing when called

I have this method 我有这种方法

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));
    }
}

and I call it like this 我这样称呼它

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);
        }
    }
}

The code stops executing at the WhenAll line. 该代码在WhenAll行处停止执行。

您需要将Search从async void更改为async Task,然后将Main中的Wait()更改为-否则,它将在任务启动后退出,但没有任何等待它完成的任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM