无法从方法组转换为System.Func (Cannot convert from method g

2019-10-22 11:24发布

我打了一下,与.NET 4.0 Task类使用线程下载谷歌网页背景。 问题是,如果我的功能具有1个或多个参数,应用程序将无法编译(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>'

先感谢您!

Answer 1:

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


Answer 2:

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");
            });


文章来源: Cannot convert from method group to System.Func