2013-04-01 19 views
5

我想創建一個在後臺線程中運行另一個方法的方法。事情是這樣的:如何將方法作爲使用linq表達式的另一種方法的參數傳遞

void Method1(string param) 
{ 
    // Some Code 
} 

void Method2(string param) 
{ 
    // Some Code 
} 

void RunInThread(AMethod m) 
{ 
    //Run the method in a background thread 
} 
+0

你應該通過一個動作:http://msdn.microsoft.com/en-GB/library/018hxwa8.aspx –

回答

8

如果你的方法有返回值使用Func委託否則,你可以使用Action委託。 e.g:

void Method1(string param) 
{ 
    // Some Code 
} 

void Method2(string param) 
{ 
    // Some Code 
} 

void RunInThread(Action<string> m) 
{ 
    //Run the method in a background thread 
} 

然後就可以調用RunInThread這樣:

RunInThread(Method1); 
RunInThread(Method2); 
+0

你可以添加2種方式在一個單獨的線程中運行它: 'm.BeginInvoke(「Hello」,null,null);''和'Task.Factory.StartNew(()=> m(「Hello」));' –

2

我喜歡Task.Run當我只想的代碼一點點地在後臺線程中運行。它甚至看起來和你想要定義的簽名幾乎相同。許多其他過載也是如此。

Task.Run(()=>{ 
     //background method code 
    }, TResult); 

MSDN documentation

相關問題