Created
March 8, 2021 23:47
-
-
Save angellaa/7d0794b6f6a22a926273b3db272305c4 to your computer and use it in GitHub Desktop.
Deadlock in a Static Constructor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Deadlock example in a Static Constructor | |
using System; | |
using System.Threading.Tasks; | |
public static class Program | |
{ | |
// Replacing "Log" with "Console.WriteLine" works. Why? | |
static Program() => Service.Do(Log); | |
public static void Main() {} | |
private static void Log(string s) => Console.WriteLine(s); | |
} | |
internal static class Service | |
{ | |
public static void Do(Action<string> logger) => | |
DoAsync(logger).GetAwaiter().GetResult(); | |
private static async Task DoAsync(Action<string> logger) | |
{ | |
logger("Start"); | |
await Task.Delay(100); | |
logger("End"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment