我目前正在升级一些现有代码以供 windows universal 使用,并且正在努力转换命令模式以使用新的 async/await 功能。
我有一个命令调度程序类,它在自己的线程中运行并处理已添加到其队列中的命令。有问题的方法如下所示:
private List<ICommandItem> _items;
private void ProcessCommands()
{
while(_items.count > 0)
{
_items[0].Execute();
_items.RemoveAt(0);
}
}
我的问题是我的一些 ICommandItem.Execute() 方法现在需要异步,因为它们涉及文件 io 而其他方法没有异步方法。我如何修改上述模式以便:
- 我的执行者可以处理异步和非异步 ICommandItems
- 执行者仅在前一个命令完成后才开始执行命令。
我很乐意只同步执行这些方法,但现在这会导致到处都是死锁。
最佳答案
My problem is that some of my ICommandItem.Execute() methods now need to be async because they involve file io whilst others have no async methods.
从技术上讲,异步(Task
-returning)签名只意味着实现可能是异步的。因此,虽然您可以引入一个单独的异步接口(interface),但另一种方法是将现有接口(interface)更改为 Task
-returning:
interface ICommandItem
{
Task ExecuteAsync(); // Used to be "void Execute();"
}
您的同步实现将不得不更改以返回一个Task
:
Task ICommandItem.ExecuteAsync()
{
// Do synchronous work.
return Task.CompletedTask; // If you're not on 4.6 yet, you can use "Task.FromResult(0)"
}
虽然异步实现很简单:
async Task ICommandItem.ExecuteAsync()
{
await ...; // Do asynchronous work.
}
你的“运行者”可以使用await
:
private async Task ProcessCommandsAsync()
{
while(_items.count > 0)
{
await _items[0].ExecuteAsync();
_items.RemoveAt(0);
}
}
关于c# - 如何使用 async/await 实现命令模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33784841/