主題

2015-12-01 29 views
1

內TargetInvocationException中的SetValue(思考)我得到這個例外:當我插入擴展方法 '的SetProperty' 的ThreadStart內主題

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

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); 

哪裏可能是使用線程的問題? 我正在使用C#6,.NET 4.5.6。

+0

我發現這個錯誤:因爲不同的線程擁有它調用線程不能訪問該對象。我應該使用另一個suliton嗎? Dispatcher.Invoke怎麼樣?或者我如何訪問不同線程的對象,擁有它? –

回答

1

使用線程時該語句爲true:調用線程無法訪問此對象,因爲不同的線程擁有它。 假設調用線程是GUI,我不知道爲什麼你需要一個昂貴的線程來運行你的財產代碼。 要使用調度嘗試:

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