通过委托或..在类之间传递参数.
本文关键字:之间 参数 | 更新日期: 2023-09-27 18:27:47
我需要在类之间传递一些变量,我有下面的代码片段来解释这种情况。注意以下代码来自app1,SimpleScene()类是入口点。
class SimpleScene {
bool isReady;
bool result;
Protected override Run() {
// instance of class StateMonitor
StateMonitor sm = new StateMonitor;
Listener(sm);
sm.proc();
while(!isReady) {}
result = func();
if (result) {
// need to inform StateMonitor to do a certain action, e.g. set bool flag = true, and StateMonitor does something iff flag == true;
}
}
void OnReady(bool isOnReady) {
if(isOnReady)
isReady = true;
}
Private void Listener(StateMonitor sm) {
sm.OnReady += new StateMonitor.ready(OnReady);
}
bool func() {
//do something...
}
}
class StateMonitor {
public delegates void ready(bool isReady);
public event ready OnReady;
// start app2 as a new process
public void proc() {
Process p_app2 = new Process();
// omit other startinfo for app2.
p_app2.OutputDataReceived += new DataReceivedEventHandler(outputHandler);
p_app2.Start();
p_app2.BeginOutputReadLine();
}
public void outputHandler(object sender, DataReceivedEventArgs line) {
// omit output data line match
if (OnReady != null)
OnReady(true);
}
}
类StateMonitor启动另一个应用程序(比如app2),并从app2读取stdout。根据输出字符串的格式,它将执行不同的操作。
我的问题在于代码注释,一旦flag==true,我想通知StateMonitor做某些事情;我怎么能那样做?
感谢
您将想要使用线程。您将在StateMonitor中启动一个基于布尔值循环的线程。然后,当您想在该标志为true时执行某项操作时,从SimpleScene设置该布尔值。有很多例子。点击此处:
http://msdn.microsoft.com/en-us/library/7a2f3ay4(v=vs.90).aspx
Worker=StateMonitor
WorkerThreadExample=SimpleScene