Add void STA task method sync
authorThomas
Wed, 08 May 2019 11:27:41 +0200
branchsync
changeset 2625d30e7f635ac7
parent 2624 c28e59231408
child 2626 6092f345eaf9
Add void STA task method
AdapterCallbacks.cs
     1.1 --- a/AdapterCallbacks.cs	Tue Apr 30 16:47:40 2019 +0200
     1.2 +++ b/AdapterCallbacks.cs	Wed May 08 11:27:41 2019 +0200
     1.3 @@ -285,6 +285,31 @@
     1.4              thread.Start();
     1.5              return tcs.Task;
     1.6          }
     1.7 +
     1.8 +        /// <summary>
     1.9 +        /// Starts a Task with return type void on a new STA thread.
    1.10 +        /// </summary>
    1.11 +        /// <typeparam name="T">The return type of the task.</typeparam>
    1.12 +        /// <param name="func">The function this task has to complete.</param>
    1.13 +        public static Task StartSTATask(Action func)
    1.14 +        {
    1.15 +            var tcs = new TaskCompletionSource<object>();
    1.16 +            var thread = new Thread(() =>
    1.17 +            {
    1.18 +                try
    1.19 +                {
    1.20 +                    func();
    1.21 +                    tcs.SetResult(null);
    1.22 +                }
    1.23 +                catch (Exception e)
    1.24 +                {
    1.25 +                    tcs.SetException(e);
    1.26 +                }
    1.27 +            });
    1.28 +            thread.SetApartmentState(ApartmentState.STA);
    1.29 +            thread.Start();
    1.30 +            return tcs.Task;
    1.31 +        }
    1.32          #endregion
    1.33      }
    1.34  }