2017-10-11 28 views
0

我想圍繞在C#async await我的頭。我已經寫了這個有兩個文件的小窗口控制檯應用程序。從C#中調用異步函數從主#

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(); 

     } 
    } 
} 

我只是想從我main調用函數DownloadFilesAsync()。我創建了Downloader對象'd'。然而,由於它是主要的並且返回類型必須是無效的,所以它是不可能的。什麼是解決這個問題的方法?

+0

https://www.bing.com/search?q=calling+an+async+function+from+main+in+c%23 –

回答

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