Click here to Skip to main content
15,882,152 members
Articles / General Programming / Threads
Tip/Trick

Simple cross-thread solution

Rate me:
Please Sign up or sign in to vote.
2.00/5 (1 vote)
24 Jul 2013CPOL 12.4K   5   4
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)


Written By
Software Developer
Brazil Brazil
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 2 Pin
Florian Rappl24-Jul-13 5:58
professionalFlorian Rappl24-Jul-13 5:58 
GeneralRe: My vote of 2 Pin
Jean A Brandelero24-Jul-13 6:57
Jean A Brandelero24-Jul-13 6:57 
GeneralRe: My vote of 2 Pin
Florian Rappl24-Jul-13 8:59
professionalFlorian Rappl24-Jul-13 8:59 
GeneralRe: My vote of 2 Pin
Jean A Brandelero24-Jul-13 9:52
Jean A Brandelero24-Jul-13 9:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.