In my WPF application, I have class that serializes and deserializes a given object to and from JSON. If I call the deserialization method from the UI thread it works fine. However I would like it to work in the background, and whenever it's on another thread i get an "Exception has been thrown by the target of an invocation" error.
This is the deserialization method
public T ReadConfig<T>(string name)
{
InitializeFileSystem();
var ConfigPath = KnownFolders.GetPath(KnownFolder.Documents) + @"\Abc\Config\";
T returnObject = default(T);
if (string.IsNullOrEmpty(name)) return default(T);
var exists = File.Exists(ConfigPath + name + ".json");
if (!exists) return returnObject;
var serializer = new DataContractJsonSerializer(typeof(T));
StreamReader reader = new StreamReader(ConfigPath + name + ".json");
returnObject = (T)serializer.ReadObject(reader.BaseStream);
reader.Close();
return returnObject;
}
On any thread other than the UI, it fails at .ReadObect(reader.BaseStream)
Below is the where the method gets called (App.xaml.cs)
/// <summary>
/// Override Application "Entry Point"
/// </summary>
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
InitializeModel();
//Task.Run(() => { InitializeModel(); });
//ThreadPool.QueueUserWorkItem(InitializeModel);
}
private void InitializeModel(object state = null)
{
var fileSystem = new FileSystem();
CurrentIndex = fileSystem.ReadConfig<IndexModel>("Index");
CurrentIndex.Start();
}
Compiled as shown above it works fine, however if i comment out the call to InitializeModel() and instead use a new task or work item all hell breaks loose.
I'm at the end of my tether here, running this on the UI thread is not an option so any help getting this resolved would be greatly appreciated.