c# – 了解Thread / BeginInvoke? [初学者]
发布时间:2020-12-15 17:44:58 所属栏目:百科 来源:网络整理
导读:考虑代码: 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
考虑代码:
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,
BackgroundWorker 的
Thread 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); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |