2015-03-31 770 views
1

我在使用.Net 4.0任務類玩點兒,以使用線程在後臺下載谷歌網頁。問題是,如果我的函數有一個或多個參數,應用程序將無法編譯(idk如何傳遞該參數)。所以我想知道如何在DoWork()方法中傳遞函數的參數。無法從方法組轉換爲System.Func <string>

這工作:

public Task<String> DoWork() { 
     //create task, of which runs our work of a thread pool thread 
     return Task.Factory.StartNew<String>(this.DownloadString); 

    } 


    private String DownloadString() 
    { 
     using (var wc = new WebClient()) 
      return wc.DownloadString("http://www.google.com"); 
    } 

這不:

public Task<String> DoWork() { 
     //create task, of which runs our work of a thread pool thread 
     return Task.Factory.StartNew<String>(this.DownloadString); 

    } 


    private String DownloadString(String uri) 
    { 
     using (var wc = new WebClient()) 
      return wc.DownloadString(uri); 
    } 

的錯誤是:

cannot convert from 'method group' to 'System.Func<string>' 

預先感謝您!

+0

如何你的第二個片段應該知道怎麼下載?你在哪裏傳遞'uri'參數? – Blorgbeard 2015-03-31 19:17:48

+0

@Blorgbeard,問題是,我不知道如何通過它。 – 2015-03-31 19:18:46

+0

好吧,這就是編譯器錯誤。你的'DownloadString'不是'Func ',它是'Func '。 Task.StartNew期待前者,而不是後者。 – Blorgbeard 2015-03-31 19:21:59

回答

2
return Task.Factory.StartNew(() => this.DownloadString("http://....")); 
+0

代表'System.Func '不帶1個參數 – 2015-03-31 19:21:47

+0

@DanielPascal我修好了 – EZI 2015-03-31 19:22:07

+0

它的工作原理,謝謝。這很明顯,很簡單。既然你先回答,我會接受你的。 – 2015-03-31 19:31:21

3
return Task.Factory.StartNew(() => DownloadString("https://www.google.com")); 

return Task.Factory.StartNew(() => 
      { 
       using (var wc = new WebClient()) 
        return wc.DownloadString("https://www.google.com"); 
      }); 
相關問題