質問

action.Invoke() will not call the "action" Action until MethodTest is exited!

     private void MethodTest(string query)
     {
        try
        {
            var webClient = new WebClient();
            string webContent = string.Empty;
            int index;
            Action action = async delegate()
            {
                webContent = await webClient.DownloadStringTaskAsync(url);
                //Add break point above
            };

            action.Invoke();
            index = webContent.IndexOf("<div class=\"detName\">");
            // some code here
        }
        catch (WebException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Note: This would work fine!

     private async void MethodTest(string query)
     {
        try
        {
            var webClient = new WebClient();
            string webContent = string.Empty;
            int index;
            webContent = await webClient.DownloadStringTaskAsync(url);
            index = webContent.IndexOf("<div class=\"detName\">");
            // some code here
        }
        catch (WebException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
役に立ちましたか?

解決

action.Invoke will invoke the delegate immediately. However, the delegate will not complete immediately, because it is asynchronous. The delegate will call webClient.DownloadStringTaskAsync before MethodTest returns, but that's the only guarantee you have. In particular, it will not assign webContent before returning (unless your HTTP request is really, really fast).

It looks like you're trying to wrap asynchronous code in synchronous code. I don't want to say this is "doomed to fail", but it's certainly not a trivial endeavor.

The best solution is to allow your containing method to be async. I describe this in my MSDN article as "async all the way".

If you're absolutely sure that you need to call asynchronous code from synchronous code, then Stephen Toub has a good overview of the various approaches (direct blocking, blocking on the thread pool, and nested message loops). There is no "best practice" in this scenario; every approach has disadvantages and pitfalls.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top