I have a task that is looping reading on a socket:
private async void readLoop() {
while (!cts.IsCancelRequested()) {
await socket.ReceiveAsync(data, ...);
doWork(data);
}
}
And since the task need not run as soon as it is created, I'm using the Task
constructor, rather than Task.Run
.
private Task readTask = new Task(readLoop, cts, LongRunning);
// when the task need to run:
readTask.Start()
At this point it works fine, except that when the task need to finish, when I call readTask.Wait()
or await readTask
, the exceptions happened in ReceiveAsync
or doWork
are not attached to the readTask
. That means even there was exceptions, readTask.Status
is RunToComplete
and readTask.Exception
is null
. Accord. to the docs, this is due to the async method returns void, but when I tried this:
private async Task readLoop() {...}
It won't compile:
error CS0407: 'Task WebSocketInitiator.readLoop()' has the wrong return type
So is there anyway to make the task start at a later time and at the same time have it keep track of exceptions happened in the task?
A minimal test case to show the problem: https://dotnetfiddle.net/JIfDIn