Difference between Returned Task and async Task

I wrote 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 call both methods inside another async method just like below

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

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

      

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

+3


source to share


1 answer


Modifier

async

just defines that you can use the keyword await

in your function body.

from this answer:



It was introduced mainly to avoid backward compatibility issues. If the asynchronous nature of a method is to be inferred by the compiler (this will be through the detection of wait keywords), then there are subtle scenarios where existing code will suddenly be handled differently, especially when you have identifiers (variable or function names called wait).

+1


source







All Articles