在static
C#方法中,我做了var brush = new LinearGradientBrush(_snazzyGradient);
,並且此行引發異常。 _snazzyGradient
定義如下:在多線程WPF應用程序中創建LinearGradientBrush時出現InvalidOperationException
private static readonly GradientStopCollection _snazzyGradient =
new GradientStopCollection
{
new GradientStop((Color)ColorConverter.ConvertFromString("#DBF3FF"), 0.0),
new GradientStop((Color)ColorConverter.ConvertFromString("#A3CCE0"), 1.0)
};
同時包含該方法和器具_snazzyGradient
INotifyPropertyChanged
,如果它的事項,並且被用作視圖模型的類。在類的構造函數中調用使用_snazzyGradient
的靜態方法。在UserControl
類中,我使用引用_snazzyGradient
的構造函數將依賴項屬性的值設置爲該視圖模型類的新實例。
當我調試我的應用程序,在var brush = new LinearGradientBrush(_snazzyGradient);
行,我得到以下異常:
System.InvalidOperationException了抓 消息=因爲不同的線程擁有它調用線程不能訪問該對象。 源= WindowsBase 堆棧跟蹤: 在System.Windows.Threading.Dispatcher.VerifyAccess() 在System.Windows.Threading.DispatcherObject.VerifyAccess() 在System.Windows.Freezable.ReadPreamble() 在System.Windows。 Media.GradientStopCollection.OnInheritanceContextChangedCore(EventArgs的參數) 在System.Windows.DependencyObject.OnInheritanceContextChanged(EventArgs的參數) 在System.Windows.Freezable.AddInheritanceContext(DependencyObject的上下文中,屬性的DependencyProperty) 在System.Windows.DependencyObject.ProvideSelfAsInheritanceContext(DependencyObject的doValue ,DependencyProperty dp) at System.Windows.DependencyObject.ProvideSelfAsInheritanceContext(Object value ,的DependencyProperty DP) 在System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex,的DependencyProperty DP,PropertyMetadata元數據,EffectiveValueEntry oldEntry,EffectiveValueEntry & newEntry,布爾coerceWithDeferredReference,OperationType operationType) 在System.Windows.DependencyObject.SetValueCommon(的DependencyProperty DP,對象值,PropertyMetadata元數據,布爾coerceWithDeferredReference,operationType operationType,布爾isInternal) 在System.Windows.DependencyObject.SetValueInternal(的DependencyProperty DP,對象的值) 在System.Windows.Media.LinearGradientBrush..ctor(gradientStopCollection gradientStopCollection) 在LoadedTemplate。 getBackgroundForTemplateValue(String fieldName) at LoadedTemplate..ctor(ParentV iewModel視圖模型,模板模板) 在Form.LoadTemplate(模板模板) 的InnerException:
我已經改變了依賴屬性在我UserControl
以下幾點:
public ParentViewModel Data
{
get
{
return (ParentViewModel)Dispatcher.Invoke(
DispatcherPriority.Background,
(DispatcherOperationCallback)delegate
{
return GetValue(DataProperty);
},
DataProperty
);
}
set
{
Dispatcher.BeginInvoke(
DispatcherPriority.Background,
(SendOrPostCallback)delegate
{
SetValue(DataProperty, value);
},
value
);
}
}
我的問題是,我怎麼能擺脫這個InvalidOperationException
?在我的視圖模型中不得不放置一堆Dispatcher
與線程相關的調用是不對的。我應該不是將_snazzyGradient
定義爲靜態字段,但可能是從靜態方法返回的?我不知道這是否會有所幫助。我絕對想要多線程,因爲我不想在必要的文件被讀取/寫入時讓GUI陷入停頓狀態。也許我的問題源於在視圖模型中使用GradientStop
(繼承自DependencyObject
)等;也許這些應該從我的UserControl
給予視圖模型的構造函數?
不確定它是否適用於此,但在不同線程中使用它們時,應始終凍結您的畫筆。你不必擔心線程問題。 – mdm20 2010-10-19 20:25:54