Fork me on GitHub

User Interface Thread Synchronizer

With the UserInterfaceThreadSynchronizer you can execute code on the user interface thread from any thread. This is usefull when an operation runs on a worker thread and needs for example to update a label on the UI or needs to create a UI component for later usage.

The user interface thread synchronizer needs to be created on the user interface thread. Otherwise, it is not capable of switching to the user interface thread.

Later, you can use the user interface thread synchronizer to execute code on the UI thread:

This will block the worker thread and execute the action specified on the user interface thread. You can also pass up to four arguments to the Execute method:

You can return values back to the worker thread:

And you can execute the action asynchronously. Obviously, it's not possible to return a value.

Testability

For simpler tests, you can tell the user interface thread synchronizer to run synchronously by passing a SyncrhonizationContext in the constructor:

Now, all actiosn are executed synchronously when Execute or ExecuteAsync is called.