ThreadRunHelper.cs 927 B

12345678910111213141516171819202122232425262728293031323334
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace Avalonia.UnitTests;
  5. public class ThreadRunHelper
  6. {
  7. public static Task<T> RunOnDedicatedThread<T>(Func<T> cb)
  8. {
  9. // Task.Run(...).GetAwaiter().GetResult() can be inlined, so we have this cursed thing instead
  10. var tcs = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
  11. new Thread(() =>
  12. {
  13. try
  14. {
  15. tcs.SetResult(cb());
  16. }
  17. catch (Exception e)
  18. {
  19. tcs.SetException(e);
  20. }
  21. }).Start();
  22. return tcs.Task;
  23. }
  24. public static Task RunOnDedicatedThread(Action cb) => RunOnDedicatedThread<object?>(() =>
  25. {
  26. cb();
  27. return null;
  28. });
  29. public static void RunOnDedicatedThreadAndWait(Action cb) => RunOnDedicatedThread(cb).GetAwaiter().GetResult();
  30. }