等待类方法完成C#
我需要从Https源下载一个文件。 我将这样做异步(到目前为止有效): 并在完成时调用client_UploadStringCompleted()方法:等待类方法完成C#,c#,asynchronous,download,wait,C#,Asynchronous,Download,Wait,我需要从Https源下载一个文件。 我将这样做异步(到目前为止有效): 并在完成时调用client_UploadStringCompleted()方法: void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e) { //Do Check here } 到目前为止还不错。现在我将所有这些放在一个类“Functions”中,并像这样调用该方法: Functio
void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
//Do Check here
}
到目前为止还不错。现在我将所有这些放在一个类“Functions”中,并像这样调用该方法:
Functions f = new Functions();
f.doChecksbeforeDownload();
我希望doChecksbeforeDownload()等待clientUloadStringCompleted完成
如何做我告诉doChecksbeforeDownload等待直到DownloadFilesAsync中的异步调用完成并准备就绪
汉内斯我只是在这里吐痰,但这个怎么样:
In DownloadFileAsync() set a flag like DownloadInProgress
In doChecksbeforeDownload
If DownloadInProgress Then set flag WaitingForDownloadCompletion
Else Continue
In client_UploadStringCompleted()
Set DownloadInProgress = false
If WaitingForDownloadCompletion Then call doChecksbeforeDownload()
您可以在类级别创建bool变量,如 bool isFinished=false 完成后,让您的async将该值设置为true
然后将isFinished变量公开为公共值。您应该寻找一些
WaitHandle
派生类来完成任务
我会使用我认为最简单的方法之一。您会希望使用.NET中公开的同步对象 退房。这里有一段摘录:
class BasicWaitHandle
{
static EventWaitHandle _waitHandle = new AutoResetEvent (false);
static void Main()
{
new Thread (Waiter).Start();
Thread.Sleep (1000); // Pause for a second...
_waitHandle.Set(); // Wake up the Waiter.
}
static void Waiter()
{
Console.WriteLine ("Waiting...");
_waitHandle.WaitOne(); // Wait for notification
Console.WriteLine ("Notified");
}
}
注意:小心将重置事件设置为静态等。这样会引入线程安全问题。为了简单起见,上面的示例只是静态的
在本例中,您希望使autoreset事件成为执行异步操作的类的成员。在函数中,启动异步调用后,等待句柄。在完成事件中,设置应取消阻止等待句柄的事件
考虑到您可能希望为WaitOne()的调用引入超时,等等。我可以在一个简单的WHILE循环中这样做吗?或者我必须把它放在自己的线程中,然后看着它运行吗?在doChecksbeforeDownload中,如果DownloadInProgress,则设置WaitingForDownloadCompletion标志,否则需要继续循环。下载完成后,将触发UploadStringCompletedEventHandler。您所写的学员随后会在下载前呼叫doChecksbeforeDownload,但现在表示下载已在进行的标志已被清除,因此可以继续进行其余工作。您好,感谢您的回答:与之前的一条评论相同的问题:我可以在简单的WHILE循环中完成此操作吗?或者我必须把它放在自己的线程中并观察它是否在运行?你可以使用while循环,但是你的CPU负载是多少。在while循环中运行查询或其他方法很容易消耗资源。考虑使用线程。睡眠,以避免检查所有的时间。
class BasicWaitHandle
{
static EventWaitHandle _waitHandle = new AutoResetEvent (false);
static void Main()
{
new Thread (Waiter).Start();
Thread.Sleep (1000); // Pause for a second...
_waitHandle.Set(); // Wake up the Waiter.
}
static void Waiter()
{
Console.WriteLine ("Waiting...");
_waitHandle.WaitOne(); // Wait for notification
Console.WriteLine ("Notified");
}
}