了解线程/BeginInvoke? [初学者]

发布于 2024-08-29 20:25:03 字数 776 浏览 7 评论 0 原文

考虑代码:

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

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

/Moberg

Consider the code:

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);
    }
}

Is (1) an acceptable way of easy starting some work in a seperate thread? If not a better alternative would be much appreciated.

Is (2) doing the same? I guess what I ask is if a new thread is started, or..

Hope you can help a beginner to a better understanding :)

/Moberg

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

や三分注定 2024-09-05 20:25:03

(1) 并不是一个丑陋的黑客,但它不是现在处理线程的“最”方式。 线程池线程通过BeginInvoke/EndInvokeBackgroundWorker.NET 4.0 中的任务并行库 是最佳选择。

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

编辑: (2) 应该看起来与 (1) 相当:

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

(1) is not an ugly hack, but it is not "the" way of doing threads these days. Thread Pool threads via BeginInvoke/EndInvoke, BackgroundWorker and the Task Parallel Library in .NET 4.0 are the way to go.

(2) is good, BUT you need to pair your BeginInvoke with an EndInvoke somewhere. Assign the new Action<string> to a variable and then call x.EndInvoke() manually on it in your main thread or in a completion method (2nd parameter to BeginInvoke). See here as a decent reference.

Edit: here's how (2) should look to be reasonably equivalent to (1):

    var thread2 = new Action<string>(this.work.DoStuff);
    var result = thread2.BeginInvoke(hello, null, null);
    thread2.EndInvoke(result);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文