gpt4 book ai didi

c# - 在 MVVM 类初始化后执行异步方法

转载 作者:太空宇宙 更新时间:2023-11-03 15:15:51 25 4
gpt4 key购买 nike

我想在我的应用程序初始化并出现主窗口后执行这些代码行:

if (System.IO.File.Exists("token"))
{

string[] startupStrings = Environment.GetCommandLineArgs();
await _myOneDrive.SilentLogIn();
IsActive = true;
if (startupStrings.Length > 1 && startupStrings[1] == "/a")
{
IsWorking = true;
IsActive = false;
await _myOneDrive.EjectSynchroProcedure(false);
IsActive = true;
IsWorking = false;
Application.Current.Shutdown();
}
}

不幸的是,我无法执行此操作,因为我无法在我的 MVVM 模型构造函数中使用 await 运算符。注册 Loaded 事件破坏了 MVVM 的整个想法。我读过一般不要使用 async void,而是仅在事件处理程序的逻辑等效项中使用。所以我的异步命令看起来像这样:

async void SilentLogin(object parameter)
{
await _myOneDrive.SilentLogin();
IsActive = true;
}

然后我在我的构造函数中初始化它们并将命令绑​​定到 XAML 代码中的按钮。

public MainWindowViewModel()
{
_myOneDrive = new MyOneDriveClient(PathPcDirectory, PathOneDriveDirectory, this);
LoginCommand = new RelayCommand(Login);
SilentLoginCommand = new RelayCommand(SilentLogin);
Console = "Program started";
}

它工作得很好,但我仍然无法实现初始化后运行代码的目标。我无法等待我的 async void Login(object parameter) 命令,因为它是 void 而不是 Task。此外,我无法将其更改为 Task,因为它对 RelayCommand 无效。所以我在这个循环中,真的会使用一些提示、技巧或只是指出我的错误。

最佳答案

有时我遇到了类似的问题并发现了一个非常简单的 AsyncRelayCommand 实现。

public class AsyncRelayCommand : RelayCommand
{
private readonly Func<Task> _asyncExecute;

public AsyncRelayCommand(Func<Task> asyncExecute)
: base(() => asyncExecute())
{
_asyncExecute = asyncExecute;
}

public AsyncRelayCommand(Func<Task> asyncExecute, Action execute)
: base(execute)
{
_asyncExecute = asyncExecute;
}

public Task ExecuteAsync()
{
return _asyncExecute();
}

public override void Execute(object parameter)
{
_asyncExecute();
}
}

然后只需修改您的方法以返回 Task 并将 RelayCommand 的用法替换为您新创建的 AsyncRelayCommand。对我来说效果很好。

请注意,带有参数的用法可能还无法正常工作,因此您需要对此进行一些额外的实现。对于我的情况,没有必要。但您应该了解基本概念。

关于c# - 在 MVVM 类初始化后执行异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39162696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com