我试图通过将每个进程(类)放入一个单独的线程来模拟分布式算法,因此它们将充当一个真正独立的进程。这些流程应该能够相互沟通。“在单独的线程中运行实例”的最简单方法是什么?
我所试图做的可以通过这一段代码来证明:
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
是否有可能实现这种功能?
谢谢!
如果要隔离过程,你应该使用的过程,而不是线程。线程不像真正的孤立进程。 – PVitt
当你从主线程调用p1.fun()时,第一个输出很明显。它并不清楚你想要达到什么。 –
'Run'和'Fnc'应该同时运行吗?那么你将需要多个线程。或者应该在运行'Fnc'时运行'暂停执行?或者都是短期运行特效?你想在一个单独的过程中运行它们还是只在一个单独的线程中运行它们? – Jan