加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – “在单独的线程中运行实例”的最简单方法是什么?

发布时间:2020-12-16 01:49:25 所属栏目:百科 来源:网络整理
导读:我试图通过将每个进程(类)放到一个单独的线程来模拟分布式算法,因此它们将充当真正的隔离进程.这些过程应该能够相互通信. 这段代码可以证明我想要做的事情: public class Process{ public void Run() { Console.WriteLine("Run called from thread {0}",Thr
我试图通过将每个进程(类)放到一个单独的线程来模拟分布式算法,因此它们将充当真正的隔离进程.这些过程应该能够相互通信.

这段代码可以证明我想要做的事情:

public class Process
{
    public void Run()
    {
        Console.WriteLine("Run called from thread {0}",Thread.CurrentThread.ManagedThreadId);
    }

    public void Fnc()
    {
        Console.WriteLine("Fnc called from thread {0}",Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(1000);
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine("Main is running in thread {0}",Thread.CurrentThread.ManagedThreadId);

        Process p1 = new Process();

        var t1 = new Thread(p1.Run);
        t1.Start();


        // This should call Fnc() in t1 Thread. It should also return immediatelly not waiting for method Fnc() to finish.
        p1.Fnc();

        Console.ReadLine();
    }
}

我得到这个输出:

Main is running in thread 9
Run called from thread 10
Fnc called from thread 9

我想得到这样的东西:

Main is running in thread 9
Run called from thread 10
Fnc called from thread 10

是否有可能实现这种功能?

谢谢!

解决方法

您可以使用Thread Parallel Library:

System.Threading.Tasks.Task.Factory.StartNew( ( ) => p1.Run )
    .ContinueWith( ( t ) => p1.Fnc );

或者您创建一个小帮助方法:

class Program
{
    private static Process p1 = new Process();
    static void Main()
    {
        Console.WriteLine("Main is running in thread {0}",Thread.CurrentThread.ManagedThreadId);

        var t1 = new Thread(Helper);
        t1.Start();
        Console.ReadLine();
    }

    private static Helper( )
    {
        p.Run();
        p.Fnc();
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读