开发者

C# Resource Dictionary XamlParseException - Thread Safety?

I am using static a Resource Dictionary which is initialized the following way:

static ResourceDictionary resource = new ResourceDictionary() 
{ 
    Source = new Uri(
        "pack://application:,,,/CommonResources;component/ApplicationData.xaml") 
};

The code has been working perfectly for the last few months but in the last few days I've started experiencing the following problem:

Exception of type 'System.Xaml.XamlParseException' was thrown. at System.Windows.Baml2006.Baml2006Reader.ReadObject(KeyRecord record) at System.Windows.ResourceDictionary.CreateObject(KeyRecord key) at System.Windows.ResourceDictionary.RealizeDeferContent(Object key, Object& value, Boolean& canCache) at System.Windows.ResourceDictionary.GetValueWithoutLock(Object key, Boolean& canCache开发者_StackOverflow中文版) at System.Windows.ResourceDictionary.GetValue(Object key, Boolean& canCache)

Aside from the above initialization, the data is read from the dictionary by accessing the needed item:

if (resource.Contains(key))
{
    return resource[key];
}

The only modification to the code might be related to many thread accessing the dictionary at the same time. It is also important to mention that the same code sometimes works perfectly and sometimes throws the above exception (Very inconsistent).

I Would appreciate any insights regarding the exception itself or the problem in general.


A ResourceDictionary is very different from a Dictionary<TKey,TValue>. When you read a value from a ResourceDictionary, if it doesn't have a cached value for the given key, it will parse the value from the xaml.

The xaml parser used by ResourceDictionary is not thread safe. In the ReadObject method (where the XamlParseException is thrown), it first Seeks to the location in the xaml read stream where the value is located. Then it parses the xaml at that location.

If two threads try and get a value out of a ResourceDictionary at the same time, thread A will seek to the location of the object A and begin reading. Thread B will then move the read position of the stream to the location of object B while thread A is in the middle of reading object A. And so you get a XamlParseException.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜