c# - 无法进入异步任务
问题描述
我试图通过大量类似的“如何调试异步任务”帖子和文章来使其工作,但仍然无法在我的 WPF 应用程序的异步方法中进入或获取断点来触发。无论我如何启动或运行我的任务,或者是否选择了 CLR 异常。
至于为什么要执行任务,我真的只希望我的 WPF 应用程序的 UI 在工作完成时保持响应,以便在应用程序思考时 UI 可用于排队其他工作。
更新 1:如果后面有一行代码,似乎断点没有被命中?!?!断点抛出异常。它自身的异常只是一个 File.IO 异常(我将很快修复),其中有很多文件操作需要排序,其中一个作为请求的最小示例包括在内。(异常不包含堆栈跟踪以确定哪个特定行被抛出,而无需手动注释掉它们,一次一个。)
具体来说,
const string APP_REG_NAMESPACE = "[Redacted]";
IProgress<int> progress;
IProgress<string> status;
public MainWindow() {
InitializeComponent();
this.DataContext = this;
//Allows UI to remain responsive while work is being done.
progress = new Progress<int>(UpdateProgress);
status = new Progress<string>(UpdateStatus);
//exceptions only appear here.
Task.Run(() => EvalConfig(progress, status));
}
/*Removed as seemed un-needed
async Task Async_EvalConfig() {
progress = new Progress<int>(UpdateProgress);
status = new Progress<string>(UpdateStatus);
//exceptions all thrown here.
await Task.Run(() => EvalConfig(progress, status));
}*/
//This allows breakpoints to be hit on any of the 3 lines
void EvalConfig(IProgress<int> progress, IProgress<string> status) {
//Give system a second (or 10)
Task.Delay(5000);
Thread.Sleep(5000);
return;
}
//No breakpoints are ever hit, if an exception occurs anywhere,
//even if on only the last line.
//Exceptions are only shown at the line that actually runs the task.
void EvalConfig(IProgress<int> progress, IProgress<string> status) {
//Give system a second
await Task.Delay(500);
cancellationTokenSource = new CancellationTokenSource();
//Some long duration IO work done here to prepare data load.
//[Redacted for brevity]
//Check the registry for the protocol key
if(TryGetProtocol(out string protocol)){
//Use the protocol to connect and start doing some painfully slow work
//[Truncated for brevity]
}else{
//Handle missing protocol logging and schedule for admin repair.
//[Truncated for brevity]
}
}
bool TryGetProtocol(out string strProtocol) {
strProtocol = "";
try {
using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(APP_REG_NAMESPACE)) {
if (key == null) {
return false;
} else {
Object o = key.GetValue("");//AKA (Default)
if (o == null) {
return false;
}
strProtocol = (o as String);
if (string.IsNullOrEmpty(strProtocol)) {
return false;
}
}
}
//Oddly this didn't actually catch the error
//despite being super generic.
} catch (Exception ex) {
//Handle notification of exception.
//[Truncated for brevity]
return false;
}
return true;
}
解决方案
不是一个真正的答案,但我最接近让断点再次命中。
如果在任务线程的任何地方抛出异常,断点似乎不会在任务/异步代码上命中。这个奇怪的行为调试器是由未处理的异常引起的,即使该异常发生在之后?!?!断点。
对于未来的搜索者,在清除所有未处理的异常之前,您可能无法使用 VS 调试器进入/通过您的任务代码。(即使程序编译愉快)
推荐阅读
- forms - Web2py - 如何处理自定义注册表单?
- java - 在 Spring Boot 中从 MongoDB 存储库中查找最大值和最小值
- c# - SQL 到 Linq 的转换在子查询中返回默认值
- php - 1142 尽管存在权限,但使用 PDO / mysql 给出错误
- python - Yocto Project Bitbake 意外终止
- java - 按下按钮后每 1.5 秒调用一次函数
- html - 表第一列绝对到父级
- javascript - 如何防止不同的用户通过 ajax/c# 为字段保存相同的值?
- sql-server - 将交易转为指标
- ruby - 如何将任何字符串值转换为正确的表示形式?