简体   繁体   中英

how to execute second method on same instance of thread after finishing first

Suppose I have a thread like

var th = new Thread(new ThreadStart(Method1));
th.Start();
th.Join(); //// wait for Method1 to finish

//// how to execute the Method2 on same thread th?

I want to excute Method2 on same insatnce of thread when it finishes the method Method1.

How can I do that?

Is this what you're trying to do?

using System;
using System.Threading;

public class Program
{
    public static void Main()
    {
        var th = new Thread(new ThreadStart(() =>
        {
            Method1();
            Method2();
        }

        ));
        th.Start();
        th.Join();
    }

    static void Method1()
    {
        Console.WriteLine("Method 1");
    }

    static void Method2()
    {
        Console.WriteLine("Method 2");
    }
}

If you are using Task Parallel Library you can use continuewith to line up tasks.

Task.Factory.StartNew(() => action("alpha"))
        .ContinueWith(antecendent => action("beta")) 
        .ContinueWith(antecendent => action("gamma"));

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