2011-08-23 20 views
2

我重新考慮了一些遺留代碼,並且更新了下面的ThreadStart語句中使用的Task.Execute方法,以用於其他上下文。但是現在它會導致編譯錯誤,說Task.Execute具有錯誤的返回類型。ThreadStart返回值?

這是爲什麼,我如何解決它,所以我可以保持我的返回值,但也ThreadStart?

ThreadStart start = new ThreadStart(Task.Execute); 
Thread asyncThread = new Thread(start); 
asyncThread.IsBackground = true; 
asyncThread.Start(); 

回答

4

返回類型ThreadStartvoid,因此您必須通過一個方法返回void。如果Task.Execute非空,你可以使用lambda表達式:

ThreadStart start = new ThreadStart(() => Task.Execute()); 
3

你需要寫你Execute方法的包裝不返回值,因爲ThreadStart代表希望的方法有void返回類型:

public static class Task 
{ 
    public static int Execute() 
    { 
     //blah blah blah 

     return 1; 
    } 

    public static void ExecuteWrapper() 
    { 
     Execute(); 
    } 
} 

然後:

ThreadStart start = new ThreadStart(Task.ExecuteWrapper); 
Thread asyncThread = new Thread(start); 
asyncThread.IsBackground = true; 
asyncThread.Start(); 

雖然可以安全地忽略返回值嗎?這通常指向一個設計問題。

0

簡單,短的包裝(除非你想記住的返回值):

ThreadStart start = new ThreadStart(() => { Task.Execute(); }); 
...