我想創建一個在後臺線程中運行另一個方法的方法。事情是這樣的:如何將方法作爲使用linq表達式的另一種方法的參數傳遞
void Method1(string param)
{
// Some Code
}
void Method2(string param)
{
// Some Code
}
void RunInThread(AMethod m)
{
//Run the method in a background thread
}
我想創建一個在後臺線程中運行另一個方法的方法。事情是這樣的:如何將方法作爲使用linq表達式的另一種方法的參數傳遞
void Method1(string param)
{
// Some Code
}
void Method2(string param)
{
// Some Code
}
void RunInThread(AMethod m)
{
//Run the method in a background thread
}
如果你的方法有返回值使用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);
你可以添加2種方式在一個單獨的線程中運行它: 'm.BeginInvoke(「Hello」,null,null);''和'Task.Factory.StartNew(()=> m(「Hello」));' –
我喜歡Task.Run
當我只想的代碼一點點地在後臺線程中運行。它甚至看起來和你想要定義的簽名幾乎相同。許多其他過載也是如此。
Task.Run(()=>{
//background method code
}, TResult);
你應該通過一個動作:http://msdn.microsoft.com/en-GB/library/018hxwa8.aspx –