I have a WPF-MVVM-application. I want to use async
and await
to make my UI responsive while loading and processing a file. I am getting an exception 'The calling thread cannot access this object because a different thread owns it' when a method which is await
ed uses logging with log4net.
// The method returns 'void' because it is used by a DelegateCommand!
private async void LoadAndProcessFileAsync()
{
this.MyBindingList.Clear(); // Works fine
var importer = await Task.Run(() => new Importer());
this.MyBindingList.Clear(); // Exception
}
All the importer does is:
public class Importer
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public Importer()
{
log.Info("Test");
}
}
If I comment out the log.Info...
and the static ILog
-variable, everything works fine. The problem also occurs if I do the following:
private async void LoadAndProcessFileAsync()
{
this.MyBindingList.Clear(); // Works fine
var test = await Task.Run(() => Math.Sqrt(9));
var importer = new Importer();
this.MyBindingList.Clear(); // Exception
}
It disappears if I don't use await
at all in the async
method.
Why does this happen? How can I use await
AND logging together? (I am using a third-party-library who uses log4net, so I can't change that code...).