Method wrapping with Task.Run (...) freezes when called in the Static constructor

I have a series of long-lasting features. I want to wrap them in Taskso that I can run all of them at the same time, and not wait for each of them to complete sequentially.

The method calls, and all the corresponding field values, methods and properties exist in the static class.

I had a problem when the constructor of the static class cannot be completed because it hangs when I complete the method with Task.Run.

In accordance with the requirements Minimum, complete and verified requirements ...

using System;
using System.Linq;
using System.Threading.Tasks;

namespace MCVEAsyncHang
{
    class Program
    {
        private static readonly string[] _foo;

        static Program()
        {
            _foo = Task.WhenAll(Task.Run(new Func<string>(One))).Result;
        }

        private static string One()
        {
            return "Foo";
        }

        private static void Print()
        {
            Console.WriteLine(
                _foo.Aggregate((total, current) => 
                     total + string.Format("{0}{1}", Environment.NewLine, current)));
        }

        static void Main(string[] args)
        {
            Print();
            Console.WriteLine("Done");
            Console.ReadLine();
        }
    }
}

, - ( , ), , .

+4
1

, , _one. , Program .

, Program , . , - , . .

, . . , . ( , , . single = threaded code - , .)

+8

Source: https://habr.com/ru/post/1663287/


All Articles