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");
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With