On 16/03/2019 03:38, Stian Zeljko Vrba wrote:
As a followup and a concrete example, here's what C++ is competing against; this piece of C# code starts an asynchronous read of a file and waits for it to complete up to some timeout value; only platform facilities are used here (i.e., no external libraries). [...] var vt = sourceFile.ReadAsync(writeTask.Data); if (vt.IsCompletedSuccessfully) { bytesRead = vt.Result; } else { var t = vt.AsTask(); if (!t.Wait(State.TransferTimeoutSeconds * 1000)) throw new AggregateException(new TimeoutException("Reader timed out."));
FWIW, using Task.Wait is in general not recommended. It's relatively safe on a worker thread that is only doing one async thing (but not always safe if there are multiple async operations). It's pretty much never safe to call it on the UI thread. In fact async-and-then-wait is an anti-pattern, since the code is not actually asynchronous at all. You should either make it actually asynchronous or use the synchronous read API instead. (As it is, the task actually continues running even when your "timeout" occurs, because you're not using task cancellation correctly.)