Class ThreadUtils
Provides helper methods for launching System.Threading.Threads.
public static class ThreadUtils
- Inheritance
-
objectThreadUtils
Methods
RunSta(Action)
Executes a delegate in a new System.Threading.ApartmentState.STA thread. Blocks the caller until the execution completes.
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exceptions are rethrown on calling thread.")]
public static void RunSta(Action execute)
Parameters
executeActionThe delegate to execute.
Remarks
This is useful for code that needs to be executed in a Single-Threaded Apartment (e.g. WinForms code) when the calling thread is not set up to handle COM.
RunSta<T>(Func<T>)
Executes a delegate in a new System.Threading.ApartmentState.STA thread. Blocks the caller until the execution completes.
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exceptions are rethrown on calling thread.")]
public static T RunSta<T>(Func<T> execute)
Parameters
executeFunc<T>The delegate to execute.
Returns
- T
The return value of
execute
Type Parameters
TThe type of the return value of
execute.
Remarks
This is useful for code that needs to be executed in a Single-Threaded Apartment (e.g. WinForms code) when the calling thread is not set up to handle COM.
RunTask(Func<Task>)
Runs an asynchronous task and blocks until it completes. Avoids deadlocks by ignoring the System.Threading.SynchronizationContext. Rethrows exceptions thrown inside task without System.AggregateException wrapper.
public static void RunTask(Func<Task> action)
Parameters
actionFunc<Task>Callback for starting the task.
Exceptions
- TaskCanceledException
The task was cancelled.
RunTask<T>(Func<Task<T>>)
Runs an asynchronous task and blocks until it completes. Avoids deadlocks by ignoring the System.Threading.SynchronizationContext. Rethrows exceptions thrown inside task without System.AggregateException wrapper.
public static T RunTask<T>(Func<Task<T>> action)
Parameters
actionFunc<Task<T>>Callback for starting the task.
Returns
- T
Type Parameters
T
Exceptions
- TaskCanceledException
The task was cancelled.
StartAsync(ThreadStart, string?)
Starts executing a delegate in a new thread suitable for WinForms.
public static Thread StartAsync(ThreadStart execute, string? name = null)
Parameters
executeThreadStartThe delegate to execute.
namestringA short name for the new thread; can be
null.
Returns
- Thread
The newly launched thread.
StartBackground(ThreadStart, string?)
Starts executing a delegate in a new background thread (automatically terminated when application exits).
public static Thread StartBackground(ThreadStart execute, string? name = null)
Parameters
executeThreadStartThe delegate to execute.
namestringA short name for the new thread; can be
null.
Returns
- Thread
The newly launched thread.