了解Thread / BeginInvoke? [初学者]

时间:2010-04-22 14:49:08

标签: c# multithreading delegates begininvoke

考虑代码:

class Work
{
    public void DoStuff(string s)
    {
        Console.WriteLine(s);
        // .. whatever
    }
}
class Master
{
    private readonly Work work = new Work();

    public void Execute()
    {
        string hello = "hello";

        // (1) is this an ugly hack ?
        var thread1 = new Thread(new ParameterizedThreadStart(o => this.work.DoStuff((string)o)));           
        thread1.Start(hello);
        thread1.Join();

        // (2) is this similar to the one above?
        new Action<string>(s => this.work.DoStuff(s)).BeginInvoke(hello, null, null);
    }
}

(1)是否可以在单独的线程中轻松启动某些工作?如果不是更好的选择将非常感激。

(2)做同样的事吗?我想我要问的是是否启动了一个新线程,或者..

希望你能帮助初学者更好地理解:)

/莫伯格

1 个答案:

答案 0 :(得分:9)

(1)并不是一个丑陋的黑客,但它现在不是“做”线程的“方式”。通过Thread PoolBeginInvoke/EndInvoke和.NET 4.0中的BackgroundWorkerTask Parallel Library个主题是可行的方法。

(2)很好,但您需要将BeginInvokeEndInvoke配对。将新Action<string>分配给变量,然后在主线程或完成方法(第x.EndInvoke()的第2个参数)中手动调用BeginInvoke。请参阅here作为一个不错的参考。

编辑:这里的(2)应该看起来与(1)相当等价:

    var thread2 = new Action<string>(this.work.DoStuff);
    var result = thread2.BeginInvoke(hello, null, null);
    thread2.EndInvoke(result);