无法从方法组转换为System.Func <string> </string>

时间:2015-03-31 19:15:23

标签: c# wpf .net-4.0 task-parallel-library

我正在使用.Net 4.0 Task类玩一下,使用线程在后台下载谷歌网页。问题是如果我的函数有一个或多个参数,应用程序就不会编译(idk如何传递该参数)。所以我想知道如何在DoWork()方法中传递函数的参数。

这有效:

    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>'

提前谢谢!

2 个答案:

答案 0 :(得分: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");
            });

答案 1 :(得分:2)

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