繁体   English   中英

如何通过工作者角色中的非阻塞方法控制任务集合的开始和停止

[英]How do control start and stop of collection of Task Collection with non-blocking method in Worker Role

我在辅助角色的OnStart方法中具有以下内容:

// Loop through Port Mappings and start a listener for each mapping

foreach (var devicePortMapping in _listenConfig.DevicePortMappingCollection)
{
    Log.Information("Starting Listener for DeviceType {DeviceType} on {Port}", devicePortMapping.DeviceType,devicePortMapping.Port);

    _workerTasks.Add(
                    token =>
                    {
                        return
                            Task.Run(
                                () =>
                                {
                                    var listener = new InboundUdpListener(_container.Resolve<IMessagePublisher>(),
                                        devicePortMapping.DeviceType, devicePortMapping.Port);

                                    listener.Start();
                                }, token);
                    });
}

start方法是一堆无效的东西,它们是一堆RX / Udp的东西,但它是非阻塞的。

我担心Run和OnStop方法中应该包含什么内容,以确保其继续运行并正常关闭。

在此处提到的合并模式中,建议使用https://msdn.microsoft.com/en-gb/library/dn589778.aspx

try
{
  Task.WaitAny(tasks.ToArray());
}
catch (AggregateException ex)
{
  Trace.TraceError(ex.Message);

  // If any of the inner exceptions in the aggregate exception 
  // are not cancellation exceptions then re-throw the exception.
  ex.Handle(innerEx => (innerEx is OperationCanceledException));
}

但是肯定不能用,因为我的任务将完成,因为listener.start不会阻塞?

在OnStop方法中,只需使用以下命令即可:

_cancellationTokenSource.Cancel();

我对这里的功能设计有完全的控制权,也许是因为我整天都在盯着它,但我希望有人可以给我一些指导,它似乎可以工作,但感觉不对。

我决定重构设计,并在侦听器类本身内部推送多个udp侦听器的编组,以简化对worker角色本身的控制。

每当我认为可能对RX /任务/异步/等待有所了解时,就会出现表明我还有路要走的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM