I have a 3rd party library that needs to be executed in a WPF application. I know this code down bellow dose not start as WPF. Might be worth keep in mind, just have tried to break out the issue as a smaller case.
Anyway, their aint much documentation or I can do about the 3rd party library, more than it needs to be used.
Because some task are pretty long when it comes to processing and time I thought It would be a good idea to have these managed on a separate thread to avoid locking UI. So my thoughts are to have most of the work that can be done in a separate processing thread, and have the 3rd party library be called on the main UI thread where it is safe and then return data to the thread for further processing. This is because the code used in there might not be fully thread safe to be called from anywhere, as so far this has been totally out of luck.
So my current thoughts about this was to dispatch what is needed from the 3rd party library thread/task to what is registered as the main UI thread, and have collect the data and return it to the processing thread.
PreProcessing -> 3pl -> PostProcessing.
This is not fully working right now as there are no exceptions or info of why this dose not work. As it just dies at when running InvokeOnMainTread
in the ThirdPartyTest()
.
What is missing here to get this invoke to be passed as ok?
Any ideas or help would be greatly appreciated.
using System;
using System.Threading.Tasks;
using System.Windows.Threading;
namespace TestTPL
{
class Program
{
static void Main(string[] args)
{
ThreadMethods methods = new ThreadMethods();
methods.Execute();
}
}
public class ThreadMethods
{
private static ThirdPartyCaller caller;
public async void Execute()
{
//Doing some pre processing...
//Reach for 3rd party lib
caller = new ThirdPartyCaller();
int taskRes = await TestTask();
//Do some more processing of data
}
private async Task<int> TestTask()
{
return await Task.Run(() =>
{
int project = caller.ThirdPartyTest();
return project;
});
}
}
public class ThirdPartyCaller
{
private readonly Dispatcher dispatcher;
public ThirdPartyCaller()
{
dispatcher = Dispatcher.CurrentDispatcher;
}
protected TResult InvokeOnMainTread<TResult>(Func<TResult> action)
{
return dispatcher.Invoke(action);
}
public int ThirdPartyTest()
{
return InvokeOnMainTread(() =>
{
//Represents calculations done by a third pary library
return 2 + 6;
});
}
}
}