why*_*heq 3 c# delegates winforms
以下控制台应用程序运行正常 - 我很惊讶它没有错误.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用winform做类似的事情,即将消息写回到表单上的标签,那么它就更复杂,需要使用该行myProcess.SynchronizingObject = this;.为什么他们会有所不同?
Console故意将该类编写为线程安全的.你可以从任何线程调用它.它甚至可以确保不会"重叠"来自不同线程的调用. Console.Write/WriteLine是原子的.这是因为Console旨在与shell交互,shell的一个主要目的是能够从多个进程收集输入.让它能够做到这一点是一项相当大的工作,但需要做到这一点才能真正实现其目的.
GUI对象(例如标签)的设计并未考虑到这一点.
| 归档时间: |
|
| 查看次数: |
198 次 |
| 最近记录: |