在C#中从main调用异步函数

时间:2017-10-11 02:05:43

标签: c# async-await

我试图在C#中围绕async await。我写过这个有两个文件的小型Windows控制台应用程序。

Downloader.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncAwait
{
    public class Downloader
    {

        public async Task DownloadFilesAsync()
        {
            // In the Real World, we would actually do something...
            // For this example, we're just going to print file 0, file 1.
            await DownloadFile0();
            await DownloadFile1();
        }
        public async Task DownloadFile0()
        {
            Console.WriteLine("Downloading File 0");
            await Task.Delay(100);
        }

        public async Task DownloadFile1()
        {
            Console.WriteLine("Downloading File 1");
            await Task.Delay(100);
        }
    }
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AsyncAwait
{
    class Program
    {
        static void Main(string[] args)
        {
            Downloader d = new Downloader();

        }
    }
}

我只想从DownloadFilesAsync()调用函数main。我创建了Downloader对象' d。但是因为它是主要的并且返回类型必须是无效的,所以是不可能的。这有什么办法?

1 个答案:

答案 0 :(得分:3)

 Task.Run(async () => { await d.DownloadFilesAsync();}).Wait();