我試圖通過將每個進程(類)放入一個單獨的線程來模擬分佈式算法,因此它們將充當一個真正獨立的進程。這些流程應該能夠相互溝通。「在單獨的線程中運行實例」的最簡單方法是什麼?
我所試圖做的可以通過這一段代碼來證明:
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