Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / threads

Simple cross-thread solution

2.00/5 (1 vote)
24 Jul 2013CPOL 12.8K  
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:  

C#
public static System.Threadi ng.SynchronizationContext mainContext = null

In the main form initialization: 

C#
mainContext = System.Threading.SynchronizationContext.Current; 

In the secondary thread, just call use this: 

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

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)