Answer the question
In order to leave comments, you need to log in
How to run code in multithread?
Hey!
There is a class Portizan, in it the GoAsync method, In which asynchronous methods are called. Example:
class Portizan
{
void Method()
{
Random rnd = new Random();
int wait = rnd.Next(10000, 25000);
Console.WriteLine($"Будет идти {wait} мс");
System.Threading.Thread.Sleep(wait);
}
async Task MethodAsync()
{
await Task.Run(() => Method());
Console.WriteLine($"Вызвал метод MethodAsync");
}
public async Task GoAsync()
{
//await SetVarAsync();
//await SetGunAsync();
await MethodAsync();
}
}
class Test
{
public async Task ZgorAsync()
{
for (int i = 0; i < 10; i++)
{
new Thread(async () =>
{
Portizan portizan = new Portizan();
await portizan.GoAsync();
}).Start();
}
//Console.ReadLine();
}
}
Answer the question
In order to leave comments, you need to log in
What does "multi-threaded" mean?
And from what I understand, you have a lot of redundant code.
Task.Run
and so it will be executed in a separate thread
Give the created task outside
class Portizan
{
void Method()
{
Random rnd = new Random();
int wait = rnd.Next(10000, 25000);
Console.WriteLine($"Будет идти {wait} мс");
System.Threading.Thread.Sleep(wait);
}
Task MethodAsync()
{
var task = Task.Run(() => Method());
Console.WriteLine($"Вызвал метод MethodAsync");
return task;
}
public Task GoAsync()
{
return MethodAsync();
}
}
Thread.Sleep // не лучшее решение для вашей задачи, так как заблокирует поток из пула потоков.
class Test
{
public async Task ZgorAsync()
{
var tasks = Enumerable.Range(0, 10)
.Select((x) => {
Portizan portizan = new Portizan();
return portizan.GoAsync();
})
.ToArray();
await Task.WaitAll(tasks);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question