---
title: "Easier Winform UI Thread Safe Methods with DynamicProxy2 and Osherove.SimpleInterception"
url: "https://osherove.com/blog/2007/5/19/easier-winform-ui-thread-safe-methods-with-dynamicproxy2-and.md"
canonical: "https://osherove.com/blog/2007/5/19/easier-winform-ui-thread-safe-methods-with-dynamicproxy2-and.html"
published: "2007-05-19T01:16:47"
updated: "2007-05-19T01:16:47"
tags: [".NET", ".Net 2.0", "C#", "Cool Tools"]
author: "Roy Osherove"
description: "Wouldn't it be cool if you could write something like this in your winform apps? : [RunInUIThread] protected virtual void DoSomeUIStuff() { this.Text = \"hey\" } Download the binary files from here. (here are the source…"
usage: "Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page)."
license: "https://creativecommons.org/licenses/by/4.0/"
---

# Easier Winform UI Thread Safe Methods with DynamicProxy2 and Osherove.SimpleInterception

By Roy Osherove May 19, 2007 In [.NET](https://osherove.com/blog/category/net), [.Net 2.0](https://osherove.com/blog/category/net-2-0), [C#](https://osherove.com/blog/category/c), [Cool Tools](https://osherove.com/blog/category/cool-tools)

**Historical article** · Originally published May 19, 2007; technical details may be outdated.

Wouldn't it be cool if you could write something like this in your winform apps? :

**\[RunInUIThread\]
_protected virtual void DoSomeUIStuff()
{
this.Text = "hey"
}_**

**Download** [the binary files](http://files.osherove.com/downloads/osherove.ThreadSafeUI.bin.zip) from here. (here [are the source files](http://files.osherove.com/downloads/osherove.ThreadSafeUI.Src.zip))

_**\-----------------**_

_**Update**:  Hammet notes that [such a facility exists in Castle](http://svn.castleproject.org:8080/svn/castle/trunk/Facilities/Synchronize/), also here's [a thread about it](http://forum.castleproject.org/viewtopic.php?p=6738&sid=21332bdb29a662f345788d0ae7fa60b5). I feel that it is too verbose and not lightwhegith enough for me, and not as easily extensible as my version, but it's good to know that such a thing already exists!_

_\---------------------------_

Inspired by [Ayende's](http://ayende.com/) talk at [devTeach](http://devteach.com/) where he showed using [Castle Windsor](http://www.castleproject.org/), I decided to take a closer look at how to implement a UI-Thread-Safe solution for winforms, based on his talk.

With a little help from Oren, it took about 5 minutes to implement the basics using the wonderful framework known as **DynamicProxy2**, part of the Castle project.

During the past couple of days I've refactored this into a more general framework for adding custom attributes which intercept method calls on any object, and allow you to easily create your own attributes with such interception abilities.

The only catches are that for this to work

- the methods you intercept should be marked as **virtual**.
- the objects which contain these methods should not be created directly, but through a special factory class which generates a proxy that does the hard interception work.

Here's how simple it is to implement a UI-Thread safe method in a Winform application:

1. **Download** [the binary files](http://files.osherove.com/downloads/osherove.ThreadSafeUI.bin.zip) from here. (here [are the source files](http://files.osherove.com/downloads/osherove.ThreadSafeUI.Src.zip))
2. unzip the 3 dll files (osherove.simpleinterception, Castle.Core and Castle.DynamicProxy2) into a folder
3. Create a new winform project and add a reference only to **osherove.SimpleInterception.dll**.
4. Add a method named "virtual void **whatever**()" to Form1 class that looks like this with the new **RunInUIThread** attribute from the dll you just referenced:

**\[RunInUIThread\]
protected virtual void Whatever()
{
this.Text = "hey"
}**

1. Add a button to the form and in its event handler start a new thread which calls the whatever() method like this:

**protected virtual void button1\_Click(object sender, EventArgs e)
{
Thread test = new Thread(new ThreadStart(Whatever));
test.Start();
}**

1. Change the code in the Main() method under program.cs to create the form using the special factory:

**Form f = AOPFactory.Create<Form1>();
Application.Run(f);**

That's it! The **Whatever**() method will always run in the UI thread, no matter what thread calls it.

Here's how easy it is to add your own intercepting Attribute:

Simply derive from AOPAttributeBase:

> **\[AttributeUsage(AttributeTargets.Method)\]
> public class CustomLoggingAttribute:AOPAttributeBase
> {
>    protected override void InvokeBefore(AOPInvocation invocation)
>    {
>      Console.WriteLine("before method {0}...", invocation.Method.Name);
>    }**

>    **protected override void InvokeAfter(AOPInvocation invocation)
>    {
>     Console.WriteLine("after method {0}...", invocation.Method.Name);
>    }
> }**

**Download** [the binary files](http://files.osherove.com/downloads/osherove.ThreadSafeUI.bin.zip) from here. (here [are the source files](http://files.osherove.com/downloads/osherove.ThreadSafeUI.Src.zip))

## More in .NET

[All posts in .NET](https://osherove.com/blog/category/net)

- Jun 20, 2007

    ### [HTTPSimulator - Simulating HTTP Requests for unit testing made easier](https://osherove.com/blog/2007/6/20/httpsimulator-simulating-http-requests-for-unit-testing-made.html)

- Jun 5, 2007

    ### [Running Matlab, Python and Tcl scripts from .NET](https://osherove.com/blog/2007/6/5/running-matlab-python-and-tcl-scripts-from-net.html)

- Mar 4, 2007

    ### [Code Generation using LINQ Expression Trees and .NET 3.0](https://osherove.com/blog/2007/3/4/code-generation-using-linq-expression-trees-and-net-30.html)

- Feb 25, 2007

    ### [FxCop is heading in the wrong direction - No testability whatsoever](https://osherove.com/blog/2007/2/25/fxcop-is-heading-in-the-wrong-direction-no-testability-whats.html)


---

## About the author

**Roy Osherove**: Senior Solutions Architect at AWS working on AI for production and AI-driven development; author of The Art of Unit Testing and Elastic Leadership, with about 20 years of consulting and training on unit testing, TDD, team leadership and continuous delivery.

### Sites

- [RobotPaper](https://robotpaper.ai/): This blog: AI patterns and anti-patterns, AI and coding agents, and engineering leadership.
- [osherove.com](https://osherove.com): Roy's personal site. Author of The Art of Unit Testing and Elastic Leadership; consulting and training on unit testing, TDD, team leadership and continuous delivery, plus about 20 years of blog posts.
- [The Art of Unit Testing](https://www.artofunittesting.com): The Art of Unit Testing, 3rd Edition (Manning): readable, maintainable, trustworthy unit tests, plus TDD workshops in C#, JavaScript, Java and Kotlin.
- [5whys.com](https://www.5whys.com): Roy's writing on software team leadership: self-organizing teams, surviving chaos, learning mode and the Elastic Leadership model.
- [Pipeline Driven](https://pipelinedriven.org): Continuous delivery and DevOps practices: build patterns, pipeline-friendly testing, DevOps metrics and enterprise DevOps.
- [Elastic Leadership](https://www.elasticleadership.com): Elastic Leadership, Roy's framework for software team leaders (survival, learning and self-organizing modes).

### Social

- X: https://x.com/royosherove
- LinkedIn: https://www.linkedin.com/in/osherove/

### Contact

- Contact form: https://forms.gle/jQSx5KoXvrVA1JCK7

### License

Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page). License: https://creativecommons.org/licenses/by/4.0/
