E
E
estry2020-04-29 11:05:53
C++ / C#
estry, 2020-04-29 11:05:53

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();
        }
    }


And the GoAsync method is called from another class:
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();
        }
    }


How to call the GoAsync method in a multithread from the ZgorAsync method and at the same time wait for all threads?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Peter, 2020-04-29
@estry

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();
        }
    }

Only
Thread.Sleep // не лучшее решение для вашей задачи, так как заблокирует поток из пула потоков.

And the final expectation will be
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 question

Ask a Question

731 491 924 answers to any question