简体   繁体   English

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

[英]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. 我想在方法Method1完成时在相同的线程上执行Method2。

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. 如果您正在使用任务并行库,则可以使用continuewith来排列任务。

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

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

相关问题 如何在C#中的第一个和第二个方法之后执行第三个方法 - how to execute a third method after first and second method in c# 启动同一线程两次-第一个线程完成后第二次 - Start same thread twice - the second time after the first one finished 如何在第一个表单的相同线程上打开第二个表单? - How to open a second form on the same thread of the first form? 怎么做:应用程序的第一个实例将执行一个进程,第二个实例将在以后终止该进程 - How to do: The first instance of an app will execute a process, second instance will kill the process later 在第一个方法完成线程功能后启动第二个方法 c# - Start second method after first method is finished with thread functionality c# 在等待在同一个线程上执行之后如何获得延续? - How can I get the continuation after an await to execute on the same thread? 异步方法调用期间主线程完成? - Main thread finishing during asynchronous method call? 处理后完成一个线程循环 - Finishing up a thread loop after disposal 仅在成功执行第一个.exe文件后如何执行第二个.exe文件? - how to execute second .exe file only after successful execution of first .exe file? 将变量传递给异步方法后,如何将主变量中的新实例设置变量影响异步方法? - After passing variable to async method, how will setting variable to new instance in main thread affect async method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM