与winform相比,从控制台进程

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;.为什么他们会有所不同?

Ser*_*rvy 6

Console故意将该类编写为线程安全的.你可以从任何线程调用它.它甚至可以确保不会"重叠"来自不同线程的调用. Console.Write/WriteLine是原子的.这是因为Console旨在与shell交互,shell的一个主要目的是能够从多个进程收集输入.让它能够做到这一点是一项相当大的工作,但需要做到这一点才能真正实现其目的.

GUI对象(例如标签)的设计并未考虑到这一点.

  • 如果你有一个打印出"hello"的写作线和另一个打印"世界"的写作线,你将获得"hello world"或"world hello".你不会得到"helworldlo"或类似的东西.因此,您可以说`Console.Write`是原子的.它本质上不是原子的,它是原子的,因为使用锁或其他类似的机制来确保它是原子的.您可以拥有多个单独的装配操作原子. (2认同)