0

我正在尝试从在线 MSDN 文章中启动 C# WPF 应用程序的代码:“如何:在 Visual Studio 2010、Windows XP SP3、.NET4.0 中 安排用户界面 (UI) 线程上的工作”

我所做的唯一区别:

  1. 将命名空间从更改wpfApplication1 WpfApplication1(因为这与文章的“1.在Visual Studio中,创建一个WPF应用程序项目并命名它。”相矛盾。

  2. 替换了该行

    string[] files = System.IO.Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures\", "*.jpg");
    

    string[] files = System.IO.Directory.GetFiles(@"D:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\", "*.jpg");
    

    (根据我的 Windows XP 机器的配置)

但是按下按钮后,应用程序异常中断:

通过等待任务或访问其异常属性未观察到任务的异常。结果,未观察到的异常被终结器线程重新抛出

代码编译没有错误,但行:

Matrix m = PresentationSource.FromVisual(Application.Current.MainWindow)

具有波浪形下划线的 Intellisense 显示弹出警告:

“可能的‘System.NullRederenceException’”

可能的“System.NullRederenceException”

我的VS2010解决方案(试图重现这篇文章)可以从:
http ://wikisend.com/download/404394/msdnHow2ScheduleWorkOnTheUI.rar下载

这段代码有什么问题?
以及如何纠正?

更新:
问题不是如何观察异常消息,而是如何启动 MSDN 示例代码(由像我这样的初学者)

我更愿意单独询问特定于异常的问题

Update2:
Errata:
Sorry...
The application doesn't break as I wrote before.

I inserted MessageBox.Show("Finished"); at the end of button1_Click() button click event handler.

Upon first click on the button the MessageBox with "Finished!" shows up.
Upon 2nd click it Messagebox again is shown and but app also throws the mentioned above exception.

第一次点击后

And having passed through exception messages and tasks results, I cannot figure out what is wrong!
I'd still like to stress that I am interested in the working sample of article's topic and will post my questions on debugging separately in other question(s)!

Is it reproducible by others?

4

1 回答 1

1

The problem is that you have an exception that is occurring inside of your task. The message is pretty self-explanatory, but I guess only if you know about exception handling in the TPL. So, to further elaborate on your exact error:

When an exception is thrown from inside of a task, it must be "observed" in 3 different ways:

  1. Check the task's Exception property
  2. Attempt to read the task's Result property (Causing any stored exceptions to be thrown)
  3. Attach an event handler to the TaskScheduler.UnobservedTaskException

If it is not observed in any of the above ways, then the exception will finally be thrown when the garbage collector tries to finalize the task. This is the reason for the exact message you are getting. However, for the deeper, original exception you will need to do one of the 3 above steps and review the actual exception

这是关于 TPL 中异常处理的 MSDN

另外,作为一个仅供参考,似乎这个未观察到的异常可能不需要处理,但我个人还没有深入研究。尽管如此,最好像处理任何代码一样处理这些。因此,此更改不应改变您编写代码的方式。

于 2013-03-30T03:23:40.630 回答