下面的控制台应用程序可以正常运行——我很惊讶它没有出错。
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;
。为什么它们之间会有区别呢?
Console.Write
是原子的。它并不是本质上的原子性,而是因为使用锁或其他类似机制来确保它的原子性。你可以让多个程序集操作成为原子操作。 - Servy