C# async cancel with exception

Viewed 97

so - Ive written a server that will listen on a port - and you can just await it to basically hang around indefinitely. It also takes a cancellation token that kills it. Both the server and cancellation token work.

So - I have some unit tests that look like this:

    var cancel = new CancellationTokenSource();
    var server = CreateServer( cancel.Token );
    var check = await CallServer();
    Assert.Equal( something, check );
    tokenSource.Cancel();
    await server;

ie - the idea is to start a server, call it - then tell it to shut down gracefully, and finally wait around until it's done so.

ALL OF THAT WORKS.

when everything is good... however... IF I break something in the server - such that it throws an exception - the exception just vanishes - never appears anywhere - and the "await server" command hangs forever (or at least until the CI times out and kills the process)

if I put the await server = createserver on one line - the exception properly comes out. Now, obviously there's something wrong with awaiting something that's had an exception and just been cancelled, but I can't figure it out.

So - how do I fix this? What should I be doing, either to properly catch the exception or to cancel the server in a better way, or to restructure this code better?

0 Answers
Related