Cannot convert from method group to System.Func

2019-07-26 19:41发布

问题:

I'm playing a bit with the .Net 4.0 Task class to download the google webpage in background using a thread. The problem is that if my function has 1 or more parameters, the application won't compile (idk how to pass that parameter). So I wonder how can I pass the function's parameter in the DoWork() method.

This works:

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

This doesn't:

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

The error is:

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

Thank you in advance!

回答1:

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


回答2:

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

or

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