控制台应用程序终止异步调用完成之前
我目前正在写一个生成一个数字,指向一个网站上不同的图像,然后使用下载的字节流的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.
是的。使用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
}