Mob*_*erg 9 c# multithreading delegates 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);
}
}
Run Code Online (Sandbox Code Playgroud)
(1)是一种在单独的线程中轻松启动某些工作的可接受方式吗?如果不是更好的选择将非常感激.
(2)做同样的事吗?我猜我要问的是是否启动了一个新线程,或者..
希望你能帮助初学者更好地理解:)
/莫伯格
(1)不是一个丑陋的黑客,但它不是这些天做线程的"方式". 线程池通过线程BeginInvoke/EndInvoke,BackgroundWorker和任务并行库在.NET 4.0中是要走的路.
(2)很好,但你需要配对你BeginInvoke的EndInvoke某个地方.将new分配Action<string>给变量,然后x.EndInvoke()在主线程或完成方法(第2个参数BeginInvoke)中手动调用它.在这里看到一个不错的参考.
编辑:这是(2)应该看起来合理地等同于(1):
var thread2 = new Action<string>(this.work.DoStuff);
var result = thread2.BeginInvoke(hello, null, null);
thread2.EndInvoke(result);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5701 次 |
| 最近记录: |