8

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");
    }
}
Liam Kernighan
  • 2,335
  • 1
  • 21
  • 24
  • Could you look at my UPD and say whether it's right or wrong? I don't think that the answers in questions that you marked as duplicates are exactly the same. – Liam Kernighan Mar 09 '18 at 20:10

1 Answers1

6

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

Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69