在等待异步操作在Console应用程序中结束时,如何避免使用Thread.Sleep(Int32.MaxValue)?

dev*_*ium 1 .net c# f# asynchronous webclient

我有以下代码将异步下载文件到我的硬盘驱动器,向控制台喊出当前的进度并最后退出一个再见消息:

webClient.DownloadProgressChanged.Add(fun args ->
      if (currentPercentage < args.ProgressPercentage) then
        Console.WriteLine(args.ProgressPercentage.ToString() + "%")

      currentPercentage <- args.ProgressPercentage
  )

webClient.DownloadFileCompleted.Add(fun args ->
  Console.WriteLine("Download finished!")
  Environment.Exit 0
)

webClient.DownloadFileAsync(new Uri(url_to_download),  file_name)

Thread.Sleep Int32.MaxValue
Run Code Online (Sandbox Code Playgroud)

然而,我想知道是否有更优雅的方式来实现这一点,而不必诉诸于主线程中的"永远沉睡",让程序尽头结束Environment.Exit().我对使用没有任何偏见,Environment.Exit()但如果可能的话,我想避免使用它!我能想到避免这种情况的唯一方法是生成一个新线程,然后等待它死掉,但这看起来确实很麻烦.有没有更简单的方法来完成这个?

小智 5

您可以像这样使用ResetEvent:

webClient.DownloadProgressChanged += (f,a) => ...
AutoResetEvent resetEvent = new AutoResetEvent(false);
webClient.DownloadFileCompleted += (f, a) => resetEvent.Set();
webClient.DownloadDataAsync(new Uri(url_to_download), file_name);
resetEvent.WaitOne();
Console.WriteLine("Finished");
Run Code Online (Sandbox Code Playgroud)