2011-11-24 86 views
3

我試圖通過將每個進程(類)放入一個單獨的線程來模擬分佈式算法,因此它們將充當一個真正獨立的進程。這些流程應該能夠相互溝通。「在單獨的線程中運行實例」的最簡單方法是什麼?

我所試圖做的可以通過這一段代碼來證明:

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 

是否有可能實現這種功能?

謝謝!

+1

如果要隔離過程,你應該使用的過程,而不是線程。線程不像真正的孤立進程。 – PVitt

+0

當你從主線程調用p1.fun()時,第一個輸出很明顯。它並不清楚你想要達到什麼。 –

+0

'Run'和'Fnc'應該同時運行嗎?那麼你將需要多個線程。或者應該在運行'Fnc'時運行'暫停執行?或者都是短期運行特效?你想在一個單獨的過程中運行它們還是隻在一個單獨的線程中運行它們? – Jan

回答

2

您可以使用線程並行庫:

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

使用任務的解決方案將做到這一點!謝謝。你的第二個選擇(以及@ RedHat的解決方案)只能在一個簡單的情況下工作,但我需要一個更通用的解決方案。 – jakubka

2

由於@PVitt說,這是不是你要爲客戶提供PROGRAMM的可靠的測試。你需要的是real單獨的進程。

創建一個可執行文件並使用不同的命令行參數運行它,並且/或者在使用.NET框架中可用的任何RPC之後使它們彼此「通話」。

1
Action action =() => { p.Run(); p.Fnc(); }; 
var t1 = new Thread(action); 
t1.Start(); 
2

沒有選擇特定線程來運行方法的機制,除非該線程明確設計爲支持該方法。這樣一個線程的基本要素是一個調度循環和一個線程安全的隊列來接收工作包。否則作爲producer/consumer problem在文獻中涵蓋得很好。你所要求的是實現否則簡單:

public void Run() 
{ 
    Fnc(); 
} 
0

如果使用.NET 4中,我建議使用任務(http://msdn.microsoft.com/en-us/library/system。 threading.tasks.task.aspx),它很容易管理/取消它們。

要運行你所需要這樣寫:

Task.Factory.StartNew(()=>{p.Run(); p.Fnc();}); 
相關問題