I am writing a method (in C#) that will be linked to a button in a GUI. One operation in this method is very time intensive (takes several minutes). It's a call to a normal synchronous void function which a cannot edit. In order to make the GUI responsive while the method is executed I tried to use async code:
The time intensive method:
public void TimeIntensiveFunction(string Parameter_1, DataTable Parameter_2, DataTable Parameter_3)
{
//time intensive stuff
//creates a large CSV btw.
}
This is what I came up with:
public async void ResponseToButton_Click(object sender, RoutedEventArgs e)
{
//doing some stuff
await AsyncTask_(dt, dt_2);
}
private async System.Threading.Tasks.Task AsyncTask_(DataTable dt, DataTable dt_2)
{
await System.Threading.Tasks.Task.Run(() => TimeIntensiveFunction(globalText, dt,dt_2));
}
I found a similar problem with this solution Wrapping synchronous code into asynchronous call, but when i run the code an exception is thrown that i dont understand:
System.InvalidOperationException
Nachricht = Der aufrufende Thread kann nicht auf dieses Objekt zugreifen, da sich das Objekt im Besitz eines anderen Threads befindet.
english:
System.InvalidOperationException
Nachricht = The calling thread cannot access this object because the object is owned by another thread.
is there a way someone can show me around this exception? The time intensive method is used by other methods in the code but should not be excecuted at the same time. Unfortunately I cannot show you the method itself. Or is there maybe another way to asynchronise my ResponseToButton_Clicke method, so that the GUI will still be responsive?
Thanks for your help!