【问题标题】:How to use action delegate to avoid if else如何使用动作委托来避免 if else
【发布时间】:2020-01-06 16:02:12
【问题描述】:

我有以下代码:

public class NotificationService {
    private readonly Dictionary<NotificationMessageType, Action<IList<RecipientDetail>, NotificationMessageType>> _actionMap;
    public NotificationService() [
        _actionMap = new Dictionary<NotificationMessageType, Action<IList<RecipientDetail>, NotificationMessageType>> ();
        _actionMap.Add(NotificationMessageType.SessionBookedReminder, new Action<IList<RecipientDetail>, NotificationMessageType>(GenerateNotificationsAsync)); //getting errror here because of async await
    }
    public async Task GenerateNotificationsAsync(IList<RecipientDetail> usersToNotify, NotificationMessageType messageType)
    {

如果这里有其他情况,想避免:

        if(messageType == NotificationMessageType.SessionBookedReminder)
        {
            await Task.WhenAll(usersToNotify.Select(u => GenerateBookingNotificationAsync(u, messageType)).ToArray());
        }
        else
        {
            await Task.WhenAll(usersToNotify.Select(u => SendNotificationAsync(u, messageType)).ToArray());
        }
    }

    public async Task GenerateNotificationsAsync(IList<RecipientDetail> usersToNotify, NotificationMessageType messageType)
    {
    }

    public async Task GenerateBookingNotificationAsync(RecipientDetail userToNotify, NotificationMessageType messageType)
    { 
    }

}

我如何使用动作委托来避免 if else。我尝试了以下操作,但由于异步等待而出错。

任何人都可以帮助如何做正确的方式?

谢谢

【问题讨论】:

  • await Task.WhenAll(usersToNotify.Select(u =&gt; messageType == NotificationMessageType.SessionBookedReminder ? GenerateBookingNotificationAsync(u, messageType) : SendNotificationAsync(u, messageType)).ToArray()); 你真的需要委托吗?

标签: c# .net delegates


【解决方案1】:

你的字典必须匹配方法声明,你的方法返回一个任务,所以你的

Action<IList<RecipientDetail>, NotificationMessageType>

必须改成类似

Func<IList<RecipientDetail>, NotificationMessageType,Task>

您的方法必须返回一个任务才能以异步/等待方式使用它

【讨论】:

  • 谢谢。有没有办法在 Action 委托中使用 async await,而不是使用带有 return 作为 Task 的 func?
  • 为什么,目的是什么?如果你的程序是异步的,它应该一直是异步的,一个不返回任务的动作不会是异步的,因此停止异步“链”
  • 如果你想使用 await Task.WhenAll(.....) 那么你必须以某种方式提供一个任务集合来放入 WhenAll。如果输入来自你的字典,那么它必须要么返回一个任务,要么是一个你包装在另一个返回任务的方法中的动作
猜你喜欢
  • 1970-01-01
  • 2014-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 2011-02-10
相关资源
最近更新 更多