I have an API that needs to be called from the thread that initialized it. I want to make a wrapper that would create a thread for running all calls to the API and then allow me to await
those calls from the UI. What would be an elegant way to do this in C#, without resorting to 3rd party libraries?
I am imagining the result looking something like this:
static class SingleThreadedApi
{
public static void Init();
// Has to be called from the same thread as init.
public static double LongRunningCall();
}
class ApiWrapper
{
// ???
}
class MyWindow
{
ApiWrapper api = new();
async void OnLoad()
{
await api.InitAsync();
}
async void OnButtonClick()
{
var result = await api.LongRunningCallAsync();
answer.Text = "result: {result}";
}
}
This question is similar to Best way in .NET to manage queue of tasks on a separate (single) thread, except there tasks only had to run serially, not necessarily on the same thread.
How do I create a custom SynchronizationContext so that all continuations can be processed by my own single-threaded event loop? might be one solution, but I hope there is something better than: "not the easiest thing in the world. I have an open-source [...] implementation."