控制台应用程序终止异步调用完成之前 [英] Console App Terminating Before async Call Completion

查看:208
本文介绍了控制台应用程序终止异步调用完成之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在写一个生成一个数字,指向一个网站上不同的图像,然后使用下载的字节流的URL的C#控制台应用程序 WebClient.DownloadDataAsync()

I'm currently writing a C# console app that generates a number of URLs that point to different images on a web site and then downloads as byte streams using WebClient.DownloadDataAsync().

我的问题是,一旦第一个异步调用时,控制台应用程序认为要完成的程序,并终止之前,异步调用可以返回。通过使用 Console.Read()我可以强制控制台将保持开放,但是这似乎并不像很好的设计。此外,如果用户点击的过程中进入(而控制台等待输入),程序将终止。

My issue is that once the first asynchronous call is made, the console app considers the program to be completed and terminates before the asynchronous call can return. By using a Console.Read() I can force the console to stay open but this doesn't seem like very good design. Furthermore if the user hits enter during the process (while the console is waiting for input) the program will terminate.

有没有prevent一个更好的方式,从关闭,而我在等待一个异步调用返回控制台?

Is there a better way to prevent the console from closing while I am waiting for an asynchronous call to return?

编辑:调用是异步的,因为我提供通过控制台一个状态指示灯,用户同时下载发生

the calls are asynchronous because I am providing a status indicator via the console to the user while the downloads take place.

推荐答案

是的。使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx\">ManualResetEvent,并有异步回调调用 event.Set()。如果 event.WaitOne主程序块(),也不会退出,直到异步code完成。

Yes. Use a ManualResetEvent, and have the async callback call event.Set(). If the Main routine blocks on event.WaitOne(), it won't exit until the async code completes.

基本伪code看起来像:

The basic pseudo-code would look like:

static ManualResetEvent resetEvent = new ManualResetEvent(false);

static void Main()
{
     CallAsyncMethod();
     resetEvent.WaitOne(); // Blocks until "set"
}

void DownloadDataCallback()
{
     // Do your processing on completion...

     resetEvent.Set(); // Allow the program to exit
}

这篇关于控制台应用程序终止异步调用完成之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆