这是我的设置。
internal class MyClass
{
private ApiObject apiObject;
private bool cond1;
private bool cond2;
internal MyClass()
{
this.apiObject = new ApiObject();
this.apiObject.ApiStateUpdate += new ApiStateUpdateEventHandler(ApiStateHandler);
//wait for both conditions to be true
}
private void ApiStateHandler(string who, int howMuch)
{
if(who.Equals("Something") && howMuch == 1)
this.cond1 = true;
else if(who.Equals("SomethingElse") && howMuch == 1)
this.cond2 = true;
}
}
我怎么能等待两个条件为真?
如果我做的:
while(!(this.cond1 && this.cond2))
{
System.Threading.Thread.Sleep(1000);
}
在ApiStateHandler()
代码似乎永远不会执行。
如果我做的:
while(!(this.cond1 && this.cond2))
{
System.Windows.Forms.Application.DoEvents();
}
这工作,但似乎是对资源的浪费和黑客攻击。
基本上我想我需要一种方式wait
但没有阻塞线程。这样做的正确方法是什么?
案例2
第二种情况有些类似(和相关的),并示出了同样的问题。
internal class MyClass
{
private ApiNotifyClass apiNotifyClass;
private shouldContinue = false;
internal MyClass()
{
//in addition to the code from above
this.apiNotifyClass = new ApiNotifyClass();
this.apiNotifyClass.ApiFound += ApiNofityFoundEventHandler(ApiNotifyHandler);
}
internal void Send(SomethingToSend somethigToSend)
{
Verifyer verifier = this.apiObject.ApiGet(somethingToSend);
this.apiNotifyClass.ApiAttach(verifier);
//wait for the shouldContinue to be true
this.apiObject.ApiSend(verifier);
this.apiNotifyClass.ApiDetach(verifier);
}
private void ApiNotifyHandler()
{
this.shouldContinue = true;
}
}
当调用Send()
,所述Verifier
对象将被创建,并且该方法需要调用ApiSend()
之前等待ApiNotifyHandler
执行(即,要发生的ApiFound
事件)。
所以这和案例1的情况是一样的。我应该如何等待应继续为真?
对不起,我想尽可能提供尽可能多的信息来帮助你。
[更新]
我被迫使用的.Net 2.0。
我编辑了这个问题:限制到.Net 2.0。 – Yeseanul
@Yeseanul,我已经更新了答案。 – Noseratio
感谢您的回复。有两件事:'myObject.Initialized = delegate'应该使用'= ='而不是'=',并且'var'在.Net 2.0中不可用(也许你可以做这两个更改以便我可以接受答案)。我已经测试了第一个解决方案,它工作正常。 – Yeseanul