Home > Net >  C# SDL2 and async methods
C# SDL2 and async methods

Time:10-21

I have my SDL2 application written on C#. My application doing basic rendering and some entities logic. Because all my logic handles in synchronous way, I decided to move into asynchronous.

My entities has Task TickAsync(float deltaTime); abstract method to perform entity logic. My call stack looks like this:

  1. Task Main(string[]?);
  2. await RunAsync(CancellationToken);
  3. await ExecuteEntitiesAsync(CancellationToken);
  4. await entity.TickAsync(float);

My problem: Because I'm using SDL2 and OpenGL, these libraries needs to be worked in one thread (where SDL2 was initialized and where OpenGL context was created. As I know, when task is created, it executes in other context (can be executed in current thread or not). Because RunAsync is async method, drawcalls can be executed not in current thread (I initialized SDL2 in Main method). RunAsync must be async because it calls await Task.WhenAll() for all entities.

My question: How can I make async method to execute in current context/thread or synchronous?

CodePudding user response:

Because all my logic handles in synchronous way, I decided to move into asynchronous.

I'm really not sure if this is a good idea. Does TickAsync really have asynchronous work to do?

Assuming that this is what you need, then you can create a single-threaded SynchronizationContext, which is non-trivial. I recommend using the AsyncContext from my AsyncEx library. Then your (synchronous) Main can just call AsyncContext.Run and pass a delegate containing your top-level logic (e.g., RunAsync).

  • Related