0

Suppose I have below code:

static void Main(string[] args)
{
    println("begin s");
    Task<int> s = CaculateSometingAsync();
    println("begin s1");
    Task<int> s1 = CaculateSometingAsync1();

    println(s.Result.ToString());
    println(s1.Result.ToString());
}

static async Task<int> CaculateSometingAsync()
{

    return await Task.Factory.StartNew<int>(() =>
    {
        Thread.Sleep(1000);
        return 100;
    });
}

static Task<int> CaculateSometingAsync1()
{

    return Task.Factory.StartNew<int>(() =>
    {
        Thread.Sleep(1000);
        return 200;
    });

}

The result is as follow:

16:55:38 begin s
16:55:38 begin s1
16:55:39 100
16:55:39 200

What I know about these two functions is that they have the same behavior. Both they create one thread-pool thread to run the task.

Both

Task<int> s = CaculateSometingAsync();

and

Task<int> s1 = CaculateSometingAsync1();

don't block the main thread.

So is there any difference between this two functions?

roast_soul
  • 3,554
  • 7
  • 36
  • 73

2 Answers2

0

The difference is the way you're using it. In the first one (CaculateSometingAsync) you're declaring it as asynchronous, and then you await inside it until it's done. You then return whatever it returns.

In your second one (CaculateSometingAsync1) you just use it as a "fire and forget" kind of things, so it goes away, waits, and returns straightto where you called it from.

(and why do you use a method println to print the string ? :) )

Noctis
  • 11,507
  • 3
  • 43
  • 82
0

you await inside the CaculateSometingAsync but could await on s as the method is declared async, where as you could not await on s1 as CaculateSometingAsync1 is not declared async. The way you are using the keywords means there is no difference in bahviour

MikeW
  • 1,568
  • 2
  • 19
  • 39