【发布时间】:2017-02-21 05:42:59
【问题描述】:
Mvvm light RelayCommand 让我对 async 方法有些头疼。 WPF 按钮与以下 relayCommand 绑定:
private RelayCommand _importDeviceCommand;
/// <summary>
/// Import device button for SelectDeviceView.
/// </summary>
public RelayCommand ImportDeviceCommand
{
get
{
return _importDeviceCommand
?? (_importDeviceCommand = new RelayCommand(async () => await AddDeviceClickExecute(),
() => _selectedCableType != null
&& _selectedAddDevice != null
&& _selectedPointNames != null
&& _selectedPointNames.Any()));
}
}
我可能以某种形式滥用它,因为在方法 AddDeviceClickExecute 完成时总是偶尔遇到以下异常。
未处理的类型异常 mscorlib.dll 中发生“System.Reflection.TargetInvocationException”
- 有哪些可能的解决方案?
- 会不会与 lambda 方法调用有关?
- 因此,我如何重构 relayCommand 以使 没有使用 lambda?
编辑 1
调用的异步方法,try/catch 是不是很遗憾没有什么区别?
private async Task AddDeviceClickExecute()
{
_linkTheSocket = true;
var deviceImporter = new DeviceImporterAsync2(_projectContext, _deviceContext);
var progress = new Progress<string>(status =>
{
_importDeviceProgress = status;
RaisePropertyChanged("ImportDeviceProgress");
});
try
{
await deviceImporter.InvokeSimpleDeviceImport(UserSelectedSockets, progress);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Exception during simple device import", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
编辑 2
AddDeviceClickExecute 退出后立即发生以下异常。
编辑 3
原来我使用 async 和 relayCommand 的方式有 与我的例外无关。问题已解决。
【问题讨论】:
-
如果不检查
TargetInvocationException,很少有任何关于TargetInvocationException的有意义的言论。 -
InnerException是空的或者我不知道怎么看。在异常设置上,我启用了(公共语言运行时执行)我正在使用 Visual Studio 2015。 -
只要抛出异常就让 Visual Studio 中断调试器,您可能会遇到实际错误。您可以从异常窗口执行此操作,只需检查“公共语言运行时”,然后使错误发生。但是,请务必在完成后将其关闭,这种行为会变得非常烦人。 blogs.msdn.microsoft.com/visualstudioalm/2015/02/23/…
-
不幸的是,我已经检查了链接中提到的
Common Language Runtime Exceptions下的所有内容。感谢您的提示!
标签: c# async-await mvvm-light mscorlib