Question

I'm scheduling a series of writes to a StreamWriter in quick succession on an ExclusiveScheduler like so:

return Task.Factory.StartNew(async () => 
        {
            await _writer.WriteAsync(responseJson.ToString() + ',');
            await _writer.FlushAsync();
        }, 
        _cancel.Token, 
        TaskCreationOptions.None, 
        _writeNetworkScheduler.ExclusiveScheduler);

If I schedule writes quickly enough, I get an InvalidOperationException. After doing some digging, it looks like the writer hangs on to the last async operation performed to throw this exception. This is the only way I'm scheduling writes on this Writer.

If I change to using the non-async versions of the methods, things execute fine, but I'd like to understand why I'm getting this exception when I'm already awaiting the previous write and flush.

Was it helpful?

Solution

Yes, it is because StartNew does not understand async methods. You need to unwrap them, as such:

return Task.Factory.StartNew(async () => 
    {
        await _writer.WriteAsync(responseJson.ToString() + ',');
        await _writer.FlushAsync();
    }, 
    _cancel.Token, 
    TaskCreationOptions.DenyChildAttach, 
    _writeNetworkScheduler.ExclusiveScheduler).Unwrap();

(also, use the DenyChildAttach option for tasks intended to be consumed by await).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top