2

我使用 System.Threading.Channels 编写了异步队列。但是当我运行程序进行测试时,随机抛出以下异常并停止工作线程。

System.InvalidOperationException: The asynchronous operation has not completed.
   at System.Threading.Channels.AsyncOperation.ThrowIncompleteOperationException()
   at System.Threading.Channels.AsyncOperation`1.GetResult(Int16 token)
   at AsyncChannels.Worker() in g:\src\gitrepos\dotnet-sandbox\channelstest\AsyncChannelsTest.cs:line 26

如果异常被捕获并忽略,则代码正在运行。但是我想摆脱原因不清楚的错误。

这是我的环境和最少的代码。

  • TargetFramework = netcoreapp2.1
  • System.Threading.Channels 版本 = 4.5.0
using System.Threading.Channels;
using System.Threading;
using System.Threading.Tasks;
using System;
using System.Linq;

class AsyncChannels : IDisposable
{
    Channel<TaskCompletionSource<bool>> _Channel;
    Thread _Thread;
    CancellationTokenSource _Cancellation;
    public AsyncChannels()
    {
        _Channel = Channel.CreateUnbounded<TaskCompletionSource<bool>>();
        _Thread = new Thread(Worker);
        _Thread.Start();
        _Cancellation = new CancellationTokenSource();
    }
    private void Worker()
    {
        while (!_Cancellation.IsCancellationRequested)
        {
            // System.InvalidOperationException is thrown
            if (!_Channel.Reader.WaitToReadAsync(_Cancellation.Token).Result)
            {
                break;
            }
            while (_Channel.Reader.TryRead(out var item))
            {
                item.TrySetResult(true);
            }
        }
    }
    public void Dispose()
    {
        _Cancellation.Cancel();
        _Channel.Writer.TryComplete();
        _Thread.Join();
    }
    public Task<bool> Enqueue()
    {
        var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
        _Channel.Writer.TryWrite(tcs);
        return tcs.Task;
    }
    public static async Task Test()
    {
        using (var queue = new AsyncChannels())
        {
            for (int i = 0; i < 100000; i++)
            {
                await queue.Enqueue().ConfigureAwait(false);
            }
        }
    }
}
4

1 回答 1

5

不能直接阻止ValueTask<T>这样的:

_Channel.Reader.WaitToReadAsync(_Cancellation.Token).Result

你只能用它做两件事ValueTask<T>await它(只有一次),或者Task<T>通过调用将它转换为 a AsTask()。如果你需要做任何复杂的事情,比如await不止一次 ing 或者阻塞它,那么你需要使用AsTask().

或者,在这种情况下,只需await在标准 Channels 消费模式中使用:

class AsyncChannels : IDisposable
{
  Channel<TaskCompletionSource<bool>> _Channel;
  Task _Thread;
  CancellationTokenSource _Cancellation;
  public AsyncChannels()
  {
    _Channel = Channel.CreateUnbounded<TaskCompletionSource<bool>>();
    _Thread = Task.Run(() => WorkerAsync());
    _Cancellation = new CancellationTokenSource();
  }
  private async Task WorkerAsync()
  {
    try
    {
      while (await _Channel.Reader.WaitToReadAsync(_Cancellation.Token))
        while (_Channel.Reader.TryRead(out var item))
          item.TrySetResult(true);
    }
    catch (OperationCanceledException)
    {
    }
  }
  public void Dispose()
  {
    _Cancellation.Cancel();
    _Channel.Writer.TryComplete();
  }
  ...
}
于 2019-04-25T13:29:43.827 回答