简体   繁体   中英

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:

        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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM