I have a switch case condition with async
Task
methods inside async
Task
method Message.
async static Task Message()
{
switch (message.Text)
{
case "1":
task1().Wait();
break;
case "2":
task2().Wait();
break;
case "3":
task3().Wait();
break;
default:
break;
}
}
and task1
for example itself. When it's completed, the cycle goes back to the Message
method. task2
and task3
are similar to task1
just with different text info.
async static Task task1()
{
try
{
while (true)
{
//some code
Message().Wait();
}
}
catch (Exception ex)
{
Console.WriteLine("Error" + ex);
}
}
The problem is when some user is inside task1
(or task2
, task3
), other user can't get response from the Message
method until task1
is finished. The question is how to execute the tasks in switch case in parallel.
My main method
static void Main(string[] args)
{
try
{
Parallel.Invoke(
() => CreateHostBuilder(args).Build().Run(),
() => Message().Wait());
}
catch (Exception ex)
{
Console.WriteLine("Error" + ex);
}
}
here is CreateHostBuilder
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
//
});