Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use async/await inline in C# [duplicate]

Tags:

c#

I have the code, that runs some block asyncrously. How can I make LongOperation() to run asyncrously the "inline" way (directly from the Main method) without creating LongTask() and LongOperationAsync() functions?

class Program
{
    static void Main(string[] args)
    {
        LongOperationAsync();
        Console.WriteLine("Main thread finished.");
        Console.ReadKey();     
    }

    static void LongOperation()
    {
        Thread.Sleep(3000);
        Console.WriteLine("Work completed");
    }

    static Task LongTask()
    {
        return Task.Run(() => LongOperation());
    }

    static async void LongOperationAsync()
    {
        await LongTask();
        Console.WriteLine("Callback triggered");
    }

}

UPD

I hope I made it right. I meant, I want to make any existing function async and add some actions after it was performed without adding any new functions. Seems like solution below is working.

class Program
{

    static void Main(string[] args)
    {

        ((Action)(async () =>
        {
            await Task.Run(() => LongOperation());
            Console.WriteLine("Then callback triggered");
        }))();

        Console.WriteLine("Main thread finished first.");


        Console.ReadKey();

    }

    static void LongOperation()
    {
        Thread.Sleep(3000);
        Console.WriteLine("Work completed");
    }
}
like image 793
Liam Kernighan Avatar asked Mar 09 '18 18:03

Liam Kernighan


1 Answers

You could use the GetAwaiter().GetResult()

static void Main(string[] args)
{
    Console.WriteLine(v);
    LongOperationAsync().GetAwaiter().GetResult();
    Console.WriteLine("Main thread finished.");
    Console.ReadKey();     
}

Read more about it in this SO question

like image 168
Marcus Höglund Avatar answered Sep 28 '22 20:09

Marcus Höglund