C# 在C中从main调用异步函数#
我正试着用C#对C# 在C中从main调用异步函数#,c#,async-await,C#,Async Await,我正试着用C#对async wait进行思考。我已经编写了这个小的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
async wait
进行思考。我已经编写了这个小的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);
}
}
}
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();
}
}
}
Program.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);
}
}
}
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();
}
}
}
我只想从我的main
调用函数downloadFileAsync()
。我已经创建了下载程序对象“d”。但是,由于它是main,并且返回类型必须为void,所以不可能。这有什么办法
Task.Run(async () => { await d.DownloadFilesAsync();}).Wait();