我目前正在研究一個c#項目,我需要一個有1個參數作爲線程運行的方法。在線程中運行參數化方法
例如
public void myMethod(string path)
{
int i = 0;
while (i != 0)
{
Console.WriteLine("Number: " + i);
i++;
}
}
如何從另一個方法調用上述方法,但在線程內部運行。
感謝您提供的任何幫助。
我目前正在研究一個c#項目,我需要一個有1個參數作爲線程運行的方法。在線程中運行參數化方法
例如
public void myMethod(string path)
{
int i = 0;
while (i != 0)
{
Console.WriteLine("Number: " + i);
i++;
}
}
如何從另一個方法調用上述方法,但在線程內部運行。
感謝您提供的任何幫助。
最簡單的方法通常是使用匿名方法或lambda表達式:
string path = ...;
Thread thread = new Thread(() => MyMethod(path));
thread.Start();
您可以使用ParameterizedThreadStart
,但我一般不會。
需要注意的是,如果你在一個循環做到這一點,你需要知道正常"closing over the loop variable"危害:
// Bad
foreach (string path in list)
{
Thread thread = new Thread(() => MyMethod(path));
thread.Start();
}
// Good
foreach (string path in list)
{
string copy = path;
Thread thread = new Thread(() => MyMethod(copy));
thread.Start();
}
new Thread(o => myMethod((string)o)).Start(param);
簡單地包裹在不帶參數的方法方法調用,但它調用你的方法使用正確的參數。
public void myWrappingMethod()
{
myMethod(this.Path);
}
public void myMethod(string path)
{
// ...
}
或者,如果您有lambda可用,只需使用其中一個(按Jon Skeet的答案)。
謝謝工作很好。令人驚訝的是很難找到這個使用谷歌的答案,這比我在Google上發現的方式簡單得多,這似乎不太好,再次感謝 – Boardy