[英]Asynchronous event in c#
In my application I have three asynchronous events. 在我的应用程序中,我有三个异步事件。
After all of them are complete I need to call some Method1(). 完成所有这些后,我需要调用一些Method1()。
How can I implement this logic? 我该如何实现这个逻辑?
Update 更新
Here is one of my asynchronous events: 这是我的异步事件之一:
public static void SetBackground(string moduleName, Grid LayoutRoot)
{
var feedsModule = FeedHandler.GetInstance().ModulesSetting.Where(type => type.ModuleType == moduleName).FirstOrDefault();
if (feedsModule != null)
{
var imageResources = feedsModule.getResources().getImageResource("Background") ??
FeedHandler.GetInstance().MainApp.getResources().getImageResource("Background");
if (imageResources != null)
{
//DownLoad Image
Action<BitmapImage> onDownloaded = bi => LayoutRoot.Background = new ImageBrush() { ImageSource = bi, Stretch = Stretch.Fill };
CacheImageFile.GetInstance().DownloadImageFromWeb(new Uri(imageResources.getValue()), onDownloaded);
}
}
}
Bit field (or 3 booleans) set by each event handler. 每个事件处理程序设置的位字段(或3个布尔值)。 Each event handler checks that the condition is met then calls Method1()
每个事件处理程序检查条件是否满足,然后调用Method1()
tryMethod1()
{
if (calledEvent1 && calledEvent2 && calledEvent3) {
Method1();
calledEvent1 = false;
calledEvent2 = false;
calledEvent3 = false;
}
}
eventHandler1() {
calledEvent1 = true;
// do stuff
tryMethod1();
}
Not given any other information, what will work is to use a counter. 没有提供任何其他信息,将使用计数器。 Just an int variable that is initialized to be 3, decremented in all handlers and checked for equality to 0 and that case go on.
只是一个初始化为3的int变量,在所有处理程序中递减,并检查相等为0,然后继续。
You should use WaitHandles for this. 你应该使用WaitHandles。 Here is a quick example, but it should give you the basic idea:
这是一个简单的例子,但它应该给你一个基本的想法:
List<ManualResetEvent> waitList = new List<ManualResetEvent>() { new ManualResetEvent(false), new ManualResetEvent(false) };
void asyncfunc1()
{
//do work
waitList[0].Set();
}
void asyncfunc2()
{
//do work
waitList[1].Set();
}
void waitFunc()
{
//in non-phone apps you would wait like this:
//WaitHandle.WaitAll(waitList.ToArray());
//but on the phone 'Waitall' doesn't exist so you have to write your own:
MyWaitAll(waitList.ToArray());
}
void MyWaitAll(WaitHandle[] waitHandleArray)
{
foreach (WaitHandle wh in waitHandleArray)
{
wh.WaitOne();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.