2015-05-12 71 views
0

我創建了一個帶參數和返回值的函數。這是下面的代碼:帶返回值和參數的C#傳遞函數Thread

static void Main(string[] args) 
    { 
     string url = "URL"; 

     Thread thread = new Thread(
      () => readFile(url) 
      ); 
     thread.Start(); 
    } 

    public static bool readFile(string url) 
    {   
      bool result = true; 
      return result; 
    } 

我怎麼能從線程內部的方法返回值?

+3

您可能需要傳遞迴調。我會考慮尋找像TPL這樣的更高層次的東西('任務'),也許'異步/等待'來做到這一點。如果你真的從url中讀取文件,那麼'HttpClient'上有異步方法。 –

回答

0

傳遞給線程的方法的簽名是void method(Object),換句話說它不能返回任何東西。處理這種情況的一個方法是允許的線程和主代碼訪問相同的變量,它可以被用於信號的結果都:

class SomeClass 
{ 
    private static bool threadResult; 

    static void Main(string[] args) 
    { 
     string url = "URL"; 

     Thread thread = new Thread(() => readFile(url)); 
     thread.Start(); 
     ... 
     // when thread completed, threadResult can be read 
    } 

    private static void readFile(string url) 
    {   
     threadResult = true; 
    } 
} 
0

您應該使用任務中獲得的結果。像下面的東西

class myClass 
{ 
    static void Main(string[] args) 
    { 
    Task<ReadFileResult> task = Task<ReadFileResult>.Factory.StartNew(() => 
    { 
     string url = "URL"; 
     return readFile(url)); 
    }); 
    ReadFileResult outcome = task.Result; 
    } 

    private static ReadFileResult readFile(string url) 
    {   
    ReadFileResult r = new ReadFileResult(); 
    r.isSuccessFull = true; 
    return r; 
    } 
} 
class ReadFileResult 
{ 
    public bool isSuccessFull { get; set; } 
} 

欲瞭解更多信息,請參閱此MSDN條目。