繁体   English   中英

首先完成后如何在线程的同一实例上执行第二种方法

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

假设我有一个像

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?

我想在方法Method1完成时在相同的线程上执行Method2。

我怎样才能做到这一点?

这是您要做什么?

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");
    }
}

如果您正在使用任务并行库,则可以使用continuewith来排列任务。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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