2010-04-22 101 views
10

考虑代码:了解线程/ 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)是否也是这样做的?我猜我问的是,如果一个新的线程启动,或..

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

/莫伯格

+2

有一个伟大的文章在这里:http://ondotnet.com/pub/a/dotnet/2003 /02/24/asyncdelegates.html,它解释了线程和异步委托之间的细微差别。 – 2010-04-22 14:59:05

+0

使用与线程一样昂贵的东西,然后用Thread.Join将其浪费掉*不可*。有很多资源可以帮助您在线程和线程池线程之间进行选择。 – 2010-04-22 15:38:49

回答

9

(1)是不是一个丑陋的黑客,但这些日子不是“做线程”的“方式”。 Thread Pool线程通过BeginInvoke/EndInvoke,BackgroundWorker和NET4.0中的Task Parallel Library是要走的路。

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

编辑:这里是(2)应该如何看起来是合理等同于(1):

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