gpt4 book ai didi

c# - "run an instance in a separate Thread"最简单的方法是什么?

转载 作者:行者123 更新时间:2023-11-30 14:16:06 24 4
gpt4 key购买 nike

我试图通过将每个进程(类)放入一个单独的线程来模拟分布式算法,因此它们将充当一个真正的孤立进程。这些进程应该能够相互通信。

这段代码可以证明我正在尝试做的事情:

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

是否可以实现这种功能?

谢谢!

最佳答案

您可以使用线程并行库:

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

关于c# - "run an instance in a separate Thread"最简单的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8257115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com