InvalidOperationException thrown from StreamWriter on WriteAsync scheduled on ExclusiveScheduler

StackOverflow https://stackoverflow.com/questions/23451208

Pergunta

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.

Foi útil?

Solução

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).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top