微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 了解Thread / 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)不是一个丑陋的黑客,但是现在这不是“线程”. Thread Pool,BackgroundWorkerThread Pool线程和.NET 4.0中的 Task Parallel Library线程是可以走的路.

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

编辑:这里的方式(2)应该看起来相当于(1):

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

原文地址:https://www.jb51.cc/csharp/96824.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐