如何正确编写异步方法?

2024-03-13

所以我试图学习在 C# 中使用“async”和“await”的基础知识,但我不确定我在这里做错了什么。我期待以下输出:

Calling DoDownload
DoDownload done
[...output here...]

但我没有得到下载的输出,我也期望“完成”,但这需要一段时间。不是应该立即输出吗?另外,我似乎也无法获得字符串结果。这是我的代码:

namespace AsyncTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Debug.WriteLine("Calling DoDownload");
            DoDownloadAsync();
            Debug.WriteLine("DoDownload done");
        }

        private static async void DoDownloadAsync()
        {
            WebClient w = new WebClient();

            string txt = await w.DownloadStringTaskAsync("http://www.google.com/");
            Debug.WriteLine(txt);
        }
    }
}

要获得您想要的行为,您需要等待该过程完成后再退出Main()。为了能够知道您的流程何时完成,您需要返回Task代替void从你的函数中,你不应该返回void from a async函数,除非您正在处理事件。

正确运行的程序的重写版本将是

class Program
{
    static void Main(string[] args)
    {
        Debug.WriteLine("Calling DoDownload");
        var downloadTask = DoDownloadAsync();
        Debug.WriteLine("DoDownload done");
        downloadTask.Wait(); //Waits for the background task to complete before finishing. 
    }

    private static async Task DoDownloadAsync()
    {
        WebClient w = new WebClient();

        string txt = await w.DownloadStringTaskAsync("http://www.google.com/");
        Debug.WriteLine(txt);
    }
}

因为你不能await in Main()我必须做Wait() http://msdn.microsoft.com/en-us/library/dd235635%28v=vs.110%29.aspx函数代替。如果这是一个具有同步上下文 http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext%28v=vs.110%29.aspx我会做await downloadTask;相反,并让函数被调用async.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何正确编写异步方法? 的相关文章

随机推荐