以下控制台应用程序运行正常 - 我很惊讶它没有出错。
class DelegateExperiments
{
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//open notepad when the console begins
//create an event that fires and writes "Notepad closed" in the console
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//instance variables of the form
private const string helloText = "hello world";
private const string exitText = "you just closed notepad";
private Process myProcess;
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
static void Main(string[] args)
{
Console.WriteLine(helloText);
DelegateExperiments myInstance;
myInstance = new DelegateExperiments();
myInstance.Foo();
Console.Read();
}
void Foo()
{
myProcess = new Process();
myProcess.StartInfo.FileName = @"notepad.exe";
myProcess.Exited += MyProcessExited;
myProcess.EnableRaisingEvents = true;
//myProcess.SynchronizingObject = this;
myProcess.Start();
}
private void MyProcessExited(Object source, EventArgs e)
{
Console.WriteLine(exitText);
}
}
如果我尝试用 winform 做类似的事情,即将消息写回表单上的标签,那么它会更复杂,需要线路myProcess.SynchronizingObject = this;
才能工作。为什么它们应该不同?