.NET Core Tasks not working on OpenVZ virtual server

119 Views Asked by At

I noticed that .NET Core 3 Tasks are not working on my Ubuntu 18.04 based virtual servers (the providers are Strato.de and HostEurope.de).

Here is a very basic test program:

static void Main(string[] args) {
    Console.WriteLine("Hello");
    Task.Delay(2000).ContinueWith(_ => Console.WriteLine("Fire"));
    Thread.Sleep(5000);
    Console.WriteLine("Exit");
}

The application should print "Hello"immediately, then after 2 seconds "Fire" and finally "Exit". This works fine on my Windows computer and also on my Ubuntu 18.04 computer.

But when I run the code on the virtual servers, the second message is never printed. Also Threading.Timer and Timers.Timer have the same problem, they almost never fire (sometimes, but very rarely, they do).

EDIT: Both virtual servers run on OpenVZ, at least this is what systemd-detect-virt says. I changed the title of the question accordingly.

Any idea what the problem could be?

2

There are 2 best solutions below

0
Andi On BEST ANSWER

This is a known bug and is going to be fixed in .NET Core 3.1.2

See https://github.com/dotnet/runtime/issues/2070 and https://github.com/dotnet/coreclr/issues/26873

1
Nkosi On

If able to use an asynchronous Main, then consider the following

public static async Task Main(string[] args) {
    Console.WriteLine("Hello");
    var task1 = Task.Run(async () => {
        await Task.Delay(2000);
        Console.WriteLine("Fire");
    });
    var task2 = Task.Delay(5000);
    await Task.WhenAll(task1, task2);
    Console.WriteLine("Exit");
}

Avoid mixing asynchronous and blocking calls like Task.Delay and Thread.Sleep respectively. If going async, go all the way.

Reference Async/Await - Best Practices in Asynchronous Programming