I have a complex WPF project written in C# (.NET 4.0) which I wrote a couple of tests for (NUnit). Theses tests reside in different classes and as long as I run the tests for each class individually everything is fine. However, once I try to run all tests of all classes at once the tests of the first class succeed, but once the testrunner (Resharper or nunit-console) starts testing the remaining classes, all of them fail with the following stack trace.
System.InvalidOperationException: The calling thread cannot access this object because a different thread owns it
at System.Windows.Threading.Dispatcher.VerifyAccess()
at System.Windows.Media.Imaging.BitmapDecoder.ToString()
at System.Windows.Media.Imaging.BitmapFrameDecode.ConvertToString(String format, IFormatProvider provider)
at System.Windows.Media.ImageSource.ToString()
at MUSTANG.ShowCase.ResourceLibrary.ResourceDictionaryManager.GetUriString(String pKey) in c:\Daten\Jenkins-ci\jobs\MUSTANG-Showcase-Release-VS2010\workspace\MUSTANG-Showcase\MUSTANG.ShowCase.ResourceLibrary\ResourceDictionaryManager.cs:Zeile 49.
The corresponding code is the following:
public object GetValue(string pKey)
{
if (mDictionary.Contains(pKey))
{
return mDictionary[pKey];
}
return null;
}
public String GetUriString(string pKey)
{
object result = GetValue(pKey);
if (null == result)
{
Log.Warn(string.Format(@"Ressource '{0}' nicht gefunden!", pKey));
return "";
}
return result.ToString();
}
The exception occurs on the last line in GetUriString when the resource was an image. Nunit seems to use different threads to run the different test classes - still they are run in sequence. Is there any way to resolve this problem e.g. by either telling NUnit or the testrunners to use a single thread, to completely quit after each test class run or similar?
Edit 1: What I have tried so far:
[RequiresSTA]
attributeThe problem seems to be that NUnit uses a different thread for each class that contains test methods, so I either need to find a way to
OR
new Application();
From the stacktrace, you posted it appears that you have a 'thread affinity' problem - i.e. you are trying to update a UI element on a thread different from the one that it was created on. BitmapDecoder is derived from DispatcherObject i.e. it needs to operate on a single thread. It seems in your test run, it is being created on one thread and then method calls (ToString) are being made from a different thread.
MUSTANG.ShowCase.ResourceLibrary
across tests? How about creating a new instance for each test i.e isolating tests ?Update: I think I have it nailed down now.
.
[assembly: RequiresThread(ApartmentState.STA)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With