【问题标题】:TargetInvocationException in SetValue(Reflection) inside of ThreadThread 内部 SetValue(Reflection) 中的 TargetInvocationException
【发布时间】:2015-12-01 10:30:00
【问题描述】:

我遇到了这个异常:

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll

当我在 ThreadStart 内插入扩展方法“SetProperty”时:

Object temp = element;

PropertyInfo currentProperty = temp.GetType().GetProperty("FontSize");

object currentValue = currentProperty.GetValue(temp);

threads[i] = new Thread(
new ThreadStart(() => 
{ currentProperty.SetValue(temp, Convert.ChangeType(58, currentProperty.PropertyType), null); }));

threads[i].Start();

但是当我使用不带线程的 SetValue 时,一切正常,没有任何异常或错误。

PropertyInfo currentProperty = temp.GetType().GetProperty("FontSize");

object currentValue = currentProperty.GetValue(temp);

currentProperty.SetValue(temp, Convert.ChangeType(58, currentProperty.PropertyType), null);

使用 Thread 可能会出现什么问题? 我正在使用 C# 6、.NET 4.5.6。

【问题讨论】:

  • 我发现这个错误:调用线程无法访问这个对象,因为另一个线程拥有它。我应该使用另一个suliton吗? Dispatcher.Invoke 呢?或者如何访问拥有它的不同线程的对象?

标签: c# multithreading exception reflection


【解决方案1】:

当使用线程时,这句话是正确的:调用线程不能访问这个对象,因为另一个线程拥有它。 假设调用线程是 GUI,我不确定你为什么需要一个昂贵的线程来运行你的属性代码。 要使用调度程序尝试:

Dispatcher.Invoke(() =>
{
    // Interact with code on a different thread.
});

【讨论】:

    猜你喜欢
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多