首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在C#中从main调用异步函数

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

Stack Overflow用户
提问于 2017-10-11 02:05:43
回答 1查看 2.8K关注 0票数 0

我正试图把我的头绕在async await的C#上。我已经写了这个小窗口控制台应用程序,有两个文件。

Downloader.cs

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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‘。但是,由于它是main类型,并且返回类型必须是无效的,所以不可能。有什么办法可以绕过这件事?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-11 02:10:43

代码语言:javascript
运行
复制
 Task.Run(async () => { await d.DownloadFilesAsync();}).Wait();
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46678636

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档