ReceiveAsync
上。我希望它在超时后返回空值。
/* snipped MyContainer class */
private readonly BufferBlock<byte[]> queue = new BufferBlock<byte[]>();
public async Task ExecuteAsync(CancellationToken stoppingToken)
{
// makes no difference if creating with TaskCreationOptions.LongRunning
await Task
.Factory
.StartNew(async () =>
{
while (stoppingToken.IsCancellationRequested == false)
{
// we get here OK, but no further if i use TimeSpan for delay
// without Timespan i.e. ReceiveAsync() only, it does **not** hang
var item = await
this
.queue
.ReceiveAsync(TimeSpan.FromMilliseconds(1000));
// process it, but we never get here we sleep forever
await ProcessAsync(item);
}
} /*,TaskCreationOptions.LongRunning*/);
// we get here and print the below OK
Console.WriteLine("thread created and running");
}
// this is called by the original (or some other) thread
// either if i call this or not, the above thread code still locks on ReceiveAsync
public void Add(byte[] data)
{
Console.WriteLine("adding");
this.queue.Post(data);
Console.WriteLine("done"); // gets posted OK
}
重要更新-如果我未指定延迟,则可以正常工作
var item = await this.queue.ReceiveAsync());
如果我删除延迟,代码可以正常运行,但是我每秒进行一些后台客房整理(用于数据包计数器等,因此,如果在1秒钟之内什么都没收到,那么唤醒就很重要。)>我正在从通用的点网工作者主机调用以上代码:其他说明:
public class Worker : BackgroundService
{
private readonly MyContainer containerClass;
private readonly ILogger<Worker> logger;
public Worker(MyContainer containerClass, ILogger<Worker> logger)
{
this.containerClass = containerClass;
this.logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
this.containerClass.ExecuteAsync(stoppingToken);
while (!stoppingToken.IsCancellationRequested)
{
this.logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
以上是在由IHostBuilder
构建工作人员,而我称为Host.Run()
之后调用的。我的理解是(我显然需要处理!),因为我创建了线程,因此它应该与创建/调用它的线程完全独立(而不是阻塞)运行...换句话说,它应该能够在线程本身内调用ReceiveAsync而不被阻塞。
要么我做错了什么,但是下面的内容从不返回,即使指定了1秒超时,它也永远挂在ReceiveAsync上。我希望它在...
已抛出TimeoutException异常,但未被我的代码或Visual Studio捕获。