- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
虽然我以某种方式理解了使用 c# 进行异步编程,但仍然不明白为什么使用 void 进行异步不是更好的解决方案,然后当我想改进我的 Xamarin Forms 代码时,我发现许多 MVVM 框架使用 AsyncCommand 来避免使用 async 进行 void “不同于事件”,如下所示:
public class AsyncCommand : Command {
public AsyncCommand(Func<Task> execute) : base(() => execute()) { }
public AsyncCommand(Func<object, Task> execute) : base((arg) => execute(arg)) { }
}
但我不知道为什么 async if 命令本身不是异步的,以及如何使用带有操作的异步命令并运行这样的任务:
public AsyncCommand(Action execute) : this(() => Task.Run(execute))
public AsyncCommand(Action<object> execute) : this((arg) => Task.Run(() => execute(arg)))
最佳答案
这是我为此 NuGet 包创建的 AsyncCommand
的实现:AsyncAwaitBestPractices.MVVM .
此实现的灵感来自 @John Thiriet's博文,"Going Async With AsyncCommand" .
using System;
using System.Threading.Tasks;
using System.Windows.Input;
namespace AsyncAwaitBestPractices.MVVM
{
/// <summary>
/// An implmentation of IAsyncCommand. Allows Commands to safely be used asynchronously with Task.
/// </summary>
public sealed class AsyncCommand<T> : IAsyncCommand<T>
{
#region Constant Fields
readonly Func<T, Task> _execute;
readonly Func<object, bool> _canExecute;
readonly Action<Exception> _onException;
readonly bool _continueOnCapturedContext;
readonly WeakEventManager _weakEventManager = new WeakEventManager();
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="T:TaskExtensions.MVVM.AsyncCommand`1"/> class.
/// </summary>
/// <param name="execute">The Function executed when Execute or ExecuteAysnc is called. This does not check canExecute before executing and will execute even if canExecute is false</param>
/// <param name="canExecute">The Function that verifies whether or not AsyncCommand should execute.</param>
/// <param name="onException">If an exception is thrown in the Task, <c>onException</c> will execute. If onException is null, the exception will be re-thrown</param>
/// <param name="continueOnCapturedContext">If set to <c>true</c> continue on captured context; this will ensure that the Synchronization Context returns to the calling thread. If set to <c>false</c> continue on a different context; this will allow the Synchronization Context to continue on a different thread</param>
public AsyncCommand(Func<T, Task> execute,
Func<object, bool> canExecute = null,
Action<Exception> onException = null,
bool continueOnCapturedContext = true)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute), $"{nameof(execute)} cannot be null");
_canExecute = canExecute ?? (_ => true);
_onException = onException;
_continueOnCapturedContext = continueOnCapturedContext;
}
#endregion
#region Events
/// <summary>
/// Occurs when changes occur that affect whether or not the command should execute
/// </summary>
public event EventHandler CanExecuteChanged
{
add => _weakEventManager.AddEventHandler(value);
remove => _weakEventManager.RemoveEventHandler(value);
}
#endregion
#region Methods
/// <summary>
/// Determines whether the command can execute in its current state
/// </summary>
/// <returns><c>true</c>, if this command can be executed; otherwise, <c>false</c>.</returns>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
public bool CanExecute(object parameter) => _canExecute(parameter);
/// <summary>
/// Raises the CanExecuteChanged event.
/// </summary>
public void RaiseCanExecuteChanged() => _weakEventManager.HandleEvent(this, EventArgs.Empty, nameof(CanExecuteChanged));
/// <summary>
/// Executes the Command as a Task
/// </summary>
/// <returns>The executed Task</returns>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
public Task ExecuteAsync(T parameter) => _execute(parameter);
void ICommand.Execute(object parameter)
{
if (parameter is T validParameter)
ExecuteAsync(validParameter).SafeFireAndForget(_continueOnCapturedContext, _onException);
else if (parameter is null && !typeof(T).IsValueType)
ExecuteAsync((T)parameter).SafeFireAndForget(_continueOnCapturedContext, _onException);
else
throw new InvalidCommandParameterException(typeof(T), parameter.GetType());
}
#endregion
}
/// <summary>
/// An implmentation of IAsyncCommand. Allows Commands to safely be used asynchronously with Task.
/// </summary>
public sealed class AsyncCommand : IAsyncCommand
{
#region Constant Fields
readonly Func<Task> _execute;
readonly Func<object, bool> _canExecute;
readonly Action<Exception> _onException;
readonly bool _continueOnCapturedContext;
readonly WeakEventManager _weakEventManager = new WeakEventManager();
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="T:TaskExtensions.MVVM.AsyncCommand`1"/> class.
/// </summary>
/// <param name="execute">The Function executed when Execute or ExecuteAysnc is called. This does not check canExecute before executing and will execute even if canExecute is false</param>
/// <param name="canExecute">The Function that verifies whether or not AsyncCommand should execute.</param>
/// <param name="onException">If an exception is thrown in the Task, <c>onException</c> will execute. If onException is null, the exception will be re-thrown</param>
/// <param name="continueOnCapturedContext">If set to <c>true</c> continue on captured context; this will ensure that the Synchronization Context returns to the calling thread. If set to <c>false</c> continue on a different context; this will allow the Synchronization Context to continue on a different thread</param>
public AsyncCommand(Func<Task> execute,
Func<object, bool> canExecute = null,
Action<Exception> onException = null,
bool continueOnCapturedContext = true)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute), $"{nameof(execute)} cannot be null");
_canExecute = canExecute ?? (_ => true);
_onException = onException;
_continueOnCapturedContext = continueOnCapturedContext;
}
#endregion
#region Events
/// <summary>
/// Occurs when changes occur that affect whether or not the command should execute
/// </summary>
public event EventHandler CanExecuteChanged
{
add => _weakEventManager.AddEventHandler(value);
remove => _weakEventManager.RemoveEventHandler(value);
}
#endregion
#region Methods
/// <summary>
/// Determines whether the command can execute in its current state
/// </summary>
/// <returns><c>true</c>, if this command can be executed; otherwise, <c>false</c>.</returns>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
public bool CanExecute(object parameter) => _canExecute(parameter);
/// <summary>
/// Raises the CanExecuteChanged event.
/// </summary>
public void RaiseCanExecuteChanged() => _weakEventManager.HandleEvent(this, EventArgs.Empty, nameof(CanExecuteChanged));
/// <summary>
/// Executes the Command as a Task
/// </summary>
/// <returns>The executed Task</returns>
public Task ExecuteAsync() => _execute();
void ICommand.Execute(object parameter) => _execute().SafeFireAndForget(_continueOnCapturedContext, _onException);
#endregion
}
/// <summary>
/// Extension methods for System.Threading.Tasks.Task
/// </summary>
public static class TaskExtensions
{
/// <summary>
/// Safely execute the Task without waiting for it to complete before moving to the next line of code; commonly known as "Fire And Forget". Inspired by John Thiriet's blog post, "Removing Async Void": https://johnthiriet.com/removing-async-void/.
/// </summary>
/// <param name="task">Task.</param>
/// <param name="continueOnCapturedContext">If set to <c>true</c> continue on captured context; this will ensure that the Synchronization Context returns to the calling thread. If set to <c>false</c> continue on a different context; this will allow the Synchronization Context to continue on a different thread</param>
/// <param name="onException">If an exception is thrown in the Task, <c>onException</c> will execute. If onException is null, the exception will be re-thrown</param>
#pragma warning disable RECS0165 // Asynchronous methods should return a Task instead of void
public static async void SafeFireAndForget(this System.Threading.Tasks.Task task, bool continueOnCapturedContext = true, System.Action<System.Exception> onException = null)
#pragma warning restore RECS0165 // Asynchronous methods should return a Task instead of void
{
try
{
await task.ConfigureAwait(continueOnCapturedContext);
}
catch (System.Exception ex) when (onException != null)
{
onException?.Invoke(ex);
}
}
}
/// <summary>
/// Weak event manager that allows for garbage collection when the EventHandler is still subscribed
/// </summary>
public class WeakEventManager
{
readonly Dictionary<string, List<Subscription>> _eventHandlers = new Dictionary<string, List<Subscription>>();
/// <summary>
/// Adds the event handler
/// </summary>
/// <param name="handler">Handler</param>
/// <param name="eventName">Event name</param>
public void AddEventHandler(Delegate handler, [CallerMemberName] string eventName = "")
{
if (IsNullOrWhiteSpace(eventName))
throw new ArgumentNullException(nameof(eventName));
if (handler is null)
throw new ArgumentNullException(nameof(handler));
EventManagerService.AddEventHandler(eventName, handler.Target, handler.GetMethodInfo(), _eventHandlers);
}
/// <summary>
/// Removes the event handler.
/// </summary>
/// <param name="handler">Handler</param>
/// <param name="eventName">Event name</param>
public void RemoveEventHandler(Delegate handler, [CallerMemberName] string eventName = "")
{
if (IsNullOrWhiteSpace(eventName))
throw new ArgumentNullException(nameof(eventName));
if (handler is null)
throw new ArgumentNullException(nameof(handler));
EventManagerService.RemoveEventHandler(eventName, handler.Target, handler.GetMethodInfo(), _eventHandlers);
}
/// <summary>
/// Executes the event
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="eventArgs">Event arguments</param>
/// <param name="eventName">Event name</param>
public void HandleEvent(object sender, object eventArgs, string eventName) => EventManagerService.HandleEvent(eventName, sender, eventArgs, _eventHandlers);
}
/// <summary>
/// An Async implmentation of ICommand
/// </summary>
public interface IAsyncCommand<T> : System.Windows.Input.ICommand
{
/// <summary>
/// Executes the Command as a Task
/// </summary>
/// <returns>The executed Task</returns>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
System.Threading.Tasks.Task ExecuteAsync(T parameter);
}
/// <summary>
/// An Async implmentation of ICommand
/// </summary>
public interface IAsyncCommand : System.Windows.Input.ICommand
{
/// <summary>
/// Executes the Command as a Task
/// </summary>
/// <returns>The executed Task</returns>
System.Threading.Tasks.Task ExecuteAsync();
}
}
关于c# - 如何实现异步命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54232156/
关闭。这个问题是off-topic .它目前不接受答案。 想改进这个问题吗? Update the question所以它是on-topic用于堆栈溢出。 关闭 9 年前。 Improve this
我有一系列 SQL 命令,我想在大约 40 个不同的表上运行。必须有一种方法可以在不编写 40 条不同命令的情况下执行此操作... 我在 SQL Server 中运行它。所有表都有不同的名称,我要操作
我习惯在 PHP 中使用命令“mysql_insert_id()”来返回插入到我的数据库中的最后一行的 id。 在 C# 中的 SQLite 中是否有等效的命令? 谢谢! -阿德娜 最佳答案 选择 l
试图找出一种方法来回填 ds 分区 Hive 表的分区。 我知道如何从 CLI 运行 Hive 命令,例如 $HIVE_HOME/bin/hive -e 'select a.col from tab1
我有 .bat 文件。看起来像下一个 ....many commands1 ftp -i -s:copy.txt ...many commands2 copy.txt 包含下一个命令 open ...
基本上我想输入 show 并检查是否有 show 命令或别名已定义并触发它,如果未定义则触发 git show 。 例如 rm 应该执行 rm 但 checkout 应该执行 git checkout
我公司的主数据库是 iSeries 机器,我已经非常习惯使用 DB2 命令和结构。我现在正在尝试做一个小项目,更新一个包含超过 300 万条记录的表。我想出一种比较和“清理”数据的更快方法是使用 My
我想在带有 Node 的终端中制作一个简单的按钮板,并“blessed”用于连接或运行不同的命令。 ----------------------------------------------- _
我们有一个 selenium IDE 脚本,正在转换为 python webdriver。以下命令未转换: [openWindow | http://mywebsite.com/index.php |
我正在学习这个关于从 GIT HUB 下载和安装 Web 文件的在线教程。我进入主题:启动我们的静态网站,系统提示我输入命令以下载和安装 Web 文件。但是,当我输入命令 yarn install 时
我在 shell 脚本中使用 elif 命令时遇到问题,就像在 fortran 中一样。 我有 100 家公司的员工名单。我想屏蔽那些员工少于 500 人的公司。我的脚本是 rm -f categor
我有一些 Linux 命令可以生成 token 。我在 Linux 机器上使用操作系统库形式的 Python 自动化了这些命令。它工作正常。 但是,当我在 Windows 中尝试相同的代码时,它没有返
本文分享自华为云社区《Git你有可能不知道交互式暂存》,作者:龙哥手记。 本节中的几个交互式 Git 命令可以帮助你将文件的特定部分组合成提交。 当你在修改了大量文件后,希望这些改动能拆分为若干提交而
我想知道如何使用 IN 比较语法来做到这一点。 当前的 SQL 查询是: select * from employee where (employeeName = 'AJAY' and month(e
我在这个位置安装了 Hadoop /usr/local/hadoop$ 现在我想列出 dfs 中的文件。我使用的命令是: hduser@ubuntu:/usr/local/hadoop$ bin/ha
是否有一个单一的 docker 命令可用于清除所有内容?如果正在运行,请停止所有容器、删除所有图像、删除所有卷...等。 最佳答案 我认为没有一个命令可以做到这一点。您首先需要停止所有容器使用 $ d
我基本上是在 clojure/nrepl 模式中寻找与 C-u C-x C-e 或 C-c C-p 等效的 Scheme。 我想要一个 C-x C-e 将输出打印到缓冲区,而不是仅仅在 repl 中。
我可以在 vim 中使用 pudb(一个 ncurses Python 调试器),因为,例如,:!python %在实际的终端窗口中运行。我更喜欢使用 gvim,但 gvim 运行 :!python
我正在尝试编写一个 FFMPEG 命令: 取为 输入 一个视频 input.mp4 和一个图像 pic.jpg 作为 输出 将 input.mp4 拆分为 20 秒的视频,按顺序重命名;对于每个分割视
我想转储视频每帧的比特率。我正在尝试使用 -vstats 获取此信息命令。当我运行此命令时 - ffmpeg -i input.mp4 -vstats 它显示至少应该定义一个文件。 如果有人能建议我任
我是一名优秀的程序员,十分优秀!