Table of Contents

Class ThreadUtils

Namespace
NanoByte.Common.Threading
Assembly
NanoByte.Common.dll

Provides helper methods for launching System.Threading.Threads.

public static class ThreadUtils
Inheritance
object
ThreadUtils

Methods

RunSta(Action)

Executes a delegate in a new System.Threading.ApartmentState.STA thread. Blocks the caller until the execution completes.

public static void RunSta(Action execute)

Parameters

execute Action

The 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.

public static T RunSta<T>(Func<T> execute)

Parameters

execute Func<T>

The delegate to execute.

Returns

T

The return value of execute

Type Parameters

T

The 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

action Func<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

action Func<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

execute ThreadStart

The delegate to execute.

name string

A 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

execute ThreadStart

The delegate to execute.

name string

A short name for the new thread; can be null.

Returns

Thread

The newly launched thread.