65.9K
CodeProject is changing. Read more.
Home

Simple cross-thread solution

Jul 24, 2013

CPOL
viewsIcon

12840

Learn how to do cross-thread operarions, the easy way!

Introduction

This small article will teach you how to use SynchronizationContext and avoid cross-thread exception. In the attached sample you will find a working project. 

Background 

I was building a multi-thread application to watch some PLC and need to show the real time data on a small form, so I found the cross-thread exception... I know I can use the old school invoke method, but i don't like it, it need much work and implementation... I searched for another way and found SynchronizationContext, its simpler and fast to implement. Ahead you will find how to do this.

Using the code 

First you need to set your context, the main thread. I set it in the main form, this way:  

public static System.Threadi ng.SynchronizationContext mainContext = null; 

In the main form initialization: 

mainContext = System.Threading.SynchronizationContext.Current; 

In the secondary thread, just call use this: 

mainContext.Send(x =>
	{
		CrossThreadMethod(params);
	}, null);

Thanks for reading, you can ask anything in the comments, ill be happy to help!