[英]How can I remove seperate worker thread function and create a thread
This is the traditional thread creation code:这是传统的线程创建代码:
public static void Ping()
{
new Thread(workThreadPingRequest) { IsBackground = true }.Start();
}
private static void workThreadPingRequest()
{
line1(); //Create connection
line2(); //Ask ping
line3(); //Process the reply and close connection
}
I've got many pairs like them.我有很多像他们这样的鞋。 So how can I remove seperate worker thread function to make the code easier -to me- like below:那么如何删除单独的工作线程 function 以使代码更容易 - 对我来说 - 如下所示:
public static void Ping()
{
new Thread(new Func<void> fn = () =>
{ line1(); line2(); line3();})
{ IsBackground = true }
.Start();
}
Or is it possible?或者有可能吗?
@Cameron's answer seems like an excellent idea but if are on .net 3.5 you could use the threadpool instead: @Cameron 的回答似乎是个好主意,但如果在 .net 3.5 上,您可以改用线程池:
System.Threading.ThreadPool.QueueUserWorkItem(_ =>
{
line1();
line2();
line3();
});
Also if you really want create a new thread instead you can do this:此外,如果你真的想创建一个新线程,你可以这样做:
new Thread(() =>
{
line1();
line2();
line3();
}) { IsBackground = true }.Start();
Sounds like you are just interested in syntax enhancement?听起来您只是对语法增强感兴趣? BackgroundWorker is pretty convienent. BackgroundWorker 非常方便。
string arg = "blah...";
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s,e) =>
{
// can extract args from e
// code here
};
worker.RunAsync(args);
this code is off the top of my head so it might not be perfect, but the idea is there.这段代码不在我的脑海中,所以它可能并不完美,但这个想法就在那里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.