开发者

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()
        {
           lin开发者_C百科e1(); //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:

        public static void Ping()
        {
            new Thread(new Func<void> fn = () => 
                { line1(); line2(); line3();}) 
                { IsBackground = true }
                .Start();
        }

Or is it possible?


Have you tried using .NET 4's Tasks?

Task.Factory.StartNew(() => {
    line1();
    line2();
    line3();
});


@Cameron's answer seems like an excellent idea but if are on .net 3.5 you could use the threadpool instead:

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜