Hi
In Main i want to call Start()
C#
static void Main(string[] args)
{
Start();
}
async Task Start()
{}Thanks
Hi
In Main i want to call Start()
static void Main(string[] args)
{
Start();
}
async Task Start()
{}Thanks
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Amit MohantyRank #112 · 20K reputationPosted Apr 8, 2024, 6:53 AM EDT
If you want to call an asynchronous method Start() from the Main method, you'll need to make the Main method asynchronous as well.
using System; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { await Start(); } static async Task Start() { } }If you prefer not to make the Main method asynchronous, you can achieve this by running the asynchronous method Start() synchronously using Task.Run() inside Main().
using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Task.Run(() => Start()).GetAwaiter().GetResult(); } static async Task Start() { } }Tahir AnsariRank #366 · 6.8K reputationPosted Apr 8, 2024, 6:22 AM EDT
using System; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { await Start(); } static async Task Start() { Console.WriteLine("Async method started..."); await Task.Delay(3000); Console.WriteLine("Async method completed!"); } }Ramco RamcoRank #462 · 5.4K reputationPosted Apr 8, 2024, 6:26 AM EDT
Hi
It is giving message The await operator can only be used within an async method.
static void Main(string[] args) { await Start(); } static async Task Start() {}Thanks
Jayraj ChhayaRank #304 · 8.2K reputationPosted Apr 8, 2024, 6:29 AM EDT
using System; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { // Call the Start method asynchronously await Start(); } static async Task Start() { // Your async code inside the Start method Console.WriteLine("Starting..."); // Simulate an asynchronous operation with Task.Delay await Task.Delay(2000); // This delays execution by 2000 milliseconds (2 seconds) Console.WriteLine("Done!"); } }