2

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!

Daniel Pascal
  • 23
  • 1
  • 1
  • 3

2 Answers2

3
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");
            });
puko
  • 2,819
  • 4
  • 18
  • 27
2
return Task.Factory.StartNew(() => this.DownloadString("http://...."));
EZI
  • 15,209
  • 2
  • 27
  • 33