【问题标题】:Understanding Thread/BeginInvoke? [beginner]了解线程/BeginInvoke? [初学者]
【发布时间】:2010-04-22 14:49:07
【问题描述】:

考虑代码:

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) 是否也在做同样的事情?我想我要问的是是否启动了一个新线程,或者..

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

/莫伯格

【问题讨论】:

  • 这里有一篇很棒的文章:ondotnet.com/pub/a/dotnet/2003/02/24/asyncdelegates.html,它解释了线程和异步委托之间的细微差别。
  • 使用像线程一样昂贵的东西然后用 Thread.Join 浪费掉它是可以接受的。有许多资源可以帮助您在线程和线程池线程之间进行选择。

标签: c# multithreading delegates begininvoke


【解决方案1】:

(1) 不是一个丑陋的 hack,但它不是如今做线程的“最佳”方式。 Thread Pool 线程通过 BeginInvoke/EndInvokeBackgroundWorker 和 .NET 4.0 中的 Task Parallel Library 是可行的方法。

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

编辑:以下是 (2) 应该如何合理地等效于 (1):

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

【讨论】:

    猜你喜欢
    • 2011-02-06
    • 2012-04-14
    • 2022-11-21
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    相关资源
    最近更新 更多