Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add concurrency to synchronous program by C# async/await

I want to learn how to add concurrency to some synchronous program, and take Fibonacci algorithm as example. I wrote these code, but I found that it doesn't have any concurrency at all. All the code running in a single thread until it finish. Could anybody can explain to me why it doesn't reflect the async?

    async static Task<int> Fibonacci(int n)
    {
        if (n == 0) { return 0; }
        else if (n == 1) { return 1; }
        else
        {
            var t1 = Fibonacci(n - 1);
            var t2 = Fibonacci(n - 2);
            return (await t1) + (await t2);
        }
    }

    static int Main(string[] args)
    {
        var fib = Fibonacci(25);
        fib.Wait();
        Console.WriteLine( fib.Result );
        Console.ReadKey();
        return 0;
    }

Under Michael's prompt, I try create Task in the async function, and it works. But I noticed that an async function returns a Task type value, it is the same as Task.Run(). Both of the tasks will run immediately, but the t1 will not run into a new thread automatically. So could anyone to tell me, what's the different between these two tasks. Can I make the async function run into new thread automatically?

    async static Task<string> Async1()
    {
        return DateTime.Now.ToString();
    }
    static void Main(string[] args)
    {
        Task<string> t1 = Async1();
        Task<string> t2 = Task.Run<string>(() => { return DateTime.Now.ToString(); });
    }
like image 438
Xu Guo Avatar asked Nov 26 '25 06:11

Xu Guo


1 Answers

First, you're using an experimental CTP for the async/await model of .NET 4.5. You should expect things to behave awkwardly in such an environment.

Second, are you aware that you're sleeping indefinitely at the end?

Third, your application is essentially synchronous. You make an asynchronous task and then wait for it immediately afterward. The async/await model does not add concurrency, only asynchrony. It simply allows your application to be responsive while doing multiple things; it does not automatically parallelize. This is why your applications is acting as if it's synchronous.

like image 158
Michael J. Gray Avatar answered Nov 28 '25 15:11

Michael J. Gray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!