EventStore async calls terminate program

72 Views Asked by At

Why do these async calls terminate execution?

static void Main(string[] args)
{
    var connectionstring = "esdb+discover://127.0.0.1:2113?tls=false";
    var settings = EventStoreClientSettings.Create(connectionstring);
    conn = new EventStoreClient(settings);
    Parse(); 
}

static async void Parse()
{
    var count = await GetEventCount("test@@test");
    // can not reach here ... program ends exit code 0...
}

public static async Task<int> GetEventCount(string streamname)
{
    var l = conn.ReadStreamAsync(Direction.Backwards, streamname, StreamPosition.Start);

    var count = 0; 
    await foreach (var item in l)
    {
        count++; 
    }

    return count;
}
2

There are 2 best solutions below

2
On BEST ANSWER

You should await your async method. See also https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming

static async Task Main(string[] args)
        {
            var connectionstring = "esdb+discover://127.0.0.1:2113?tls=false";
            var settings = EventStoreClientSettings.Create(connectionstring);
            conn = new EventStoreClient(settings);
            await ParseAsync(); 

}
static async Task ParseAsync()
        {
            var count = await GetEventCount("test@@test");
// can not reach here ... program ends exit code 0...

}
    public static async Task<int> GetEventCount(string streamname)
        {
            var l = conn.ReadStreamAsync(Direction.Backwards, streamname, StreamPosition.Start);

            var count = 0; 
            await foreach (var item in l)
            {
                count++; 
            }

            return count;
        }
0
On

The root problem is that you're not waiting for the completion of Parse so the Main method just exists before it completes, thus terminating the program. Nothing else in the code cdoes in fact cause a termination.

The first possible solution is to force waiting on the call:

Parse().Wait();

Using Wait directly is often not a good option and is a frequent cause of deadlocks in more complex programs, although used here will be probably fine.

A better solution is make Main async too and just use regular async/await like everywhere else:

static async Task Main(string[] args)
{
    var connectionstring = "esdb+discover://127.0.0.1:2113?tls=false";
    var settings = EventStoreClientSettings.Create(connectionstring);
    conn = new EventStoreClient(settings);
    await Parse();
}

Both option will cause the call to Parse() to wait until completion, thus giving a chance to use its output.