Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am using a user control in windows application this project is build as class library
then i use another class library to access the windows form then changes the user controls shown in the main form, this library has another thread that waits user actions on the gui to do some work
another console application runs the second class library first thread to run windows application and the second to wait user actions and change the user controls according to user input
I faced the problem that i cannot change UI owned by another thread i passed this by using

C#
if(InvokeRequired) Invoke(new Action<object, EventArgs>(button_Click),sender,e) ;


In test it looks it is working but actually each time i invoke an event or invoke any method using this syntax i found that it is executed more than once and each time it is doubled

thank you for any help
Posted

1 solution

This is typically how I ensure the method is executed back on UI thread. Typically it would not be a button click but an event handler...

You might want to look into Synchronizing context for your library classes that run on seperate thread. You can assign the UI thread as the synchronizing context and inside your non-ui thread you can post back to the UI thread so any events raised or methods executed can be executed back to the UI thread if you are required to update UI controls.

Understanding SynchronizationContext (Part I)[^]

http://www.codeproject.com/search.aspx?q=Synchronizing+context&sbo=kw&x=0&y=0[^]


C#
private void button1_Click(object sender, EventArgs e)
       {

           if (this.InvokeRequired)
           {
               this.Invoke(new EventHandler(button1_Click), new[] { sender, e });
           }
           else
           {
               //perform UI update
           }
       }
 
Share this answer
 
Comments
Waleedkassem 14-Jul-12 4:30am    
thank you too much
Waleedkassem 14-Jul-12 5:57am    
the problem is the method is invoked more than once any idea please time after time it is doubled if i click the button 3 times the method is invoked more than 10 times
Trak4Net 14-Jul-12 6:04am    
Are you adding handler to button click? It sounds like code continues to add handler somewhere.
Waleedkassem 14-Jul-12 8:10am    
yes this is it i think i add handler to button click more than once i noticed that. and i used the invoke method within wrong control
Waleedkassem 14-Jul-12 9:43am    
its that i added the event handler more than once to the user control i need to remove all assigned event handlers

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900