4

I have written below two methods

    private Task<string> GetStringTask(string url)
    {
        var client = new WebClient();
        var task = client.DownloadDataTaskAsync(new Uri(url));

        var task2 = task.ContinueWith<string>(task1 =>
        {
            var str = Encoding.Default.GetString(task1.Result);
            Thread.Sleep(5000);
            return str;
        });

        return task2;
    }

    private async Task<string> GetStringAsyc(string url)
    {
        var client = new WebClient();
        var htmlByte = await client.DownloadDataTaskAsync(new Uri(url));
        var task2 = await Task.Factory.StartNew(() =>
        {
            var str = Encoding.Default.GetString(htmlByte);
            Thread.Sleep(2000);
            return str;
        });

        return task2;
    }

I can invoke the both the methods inside the another async method same way like below

var mystring = await GetStringTask("http://www.microsoft.com");

var mystring1 = await GetStringAsync("http://www.microsoft.com");

Both method return the same result. Can anyone explain me the difference between these two methods.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Saran
  • 835
  • 3
  • 11
  • 31

1 Answers1

1

async modifier just determines that you can use await keyword in your function body.

from this answer:

It was introduced mainly to avoid backward compatibility issues. If the async-ness of a method must be inferred by the compiler (that would be through the detection of await keywords), then there are subtle scenarios where existing code would suddenly be treated differently, notably when you have identifiers (variable or function names called await).

Community
  • 1
  • 1
farid bekran
  • 2,684
  • 2
  • 16
  • 29