-1

コードは以下です。

DoLongWork 関数を非同期で呼び出したい。

しかし、DoLongWork は何も待機しないため、コードは同期になります

DoLongWork 関数で何かを待つ必要はありません。関数自体が長時間実行されるためです。リソースを待機していません。

この悪循環から抜け出すにはどうすればよいでしょうか。

 class Program
    {
        static void Main(string[] args)
        {
            Task<int> task = Foo("Something");
            Console.WriteLine("Do it");
            Console.WriteLine("Do that");
            task.Wait();
            Console.WriteLine("Ending All");
        }
        static async Task<int> Foo(string param)
        {
            Task<int> lwAsync = DoLongWork(param);
            int res = await lwAsync;
            return res;
        }

        static async Task<int> DoLongWork(string param)
        {
            Console.WriteLine("Long Running Work is starting");
            Thread.Sleep(3000); // Simulating long work.
            Console.WriteLine("Long Running Work is ending");
            return 0;
        }
    }
4

1 に答える 1