Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
Hi all,

im done some database coding in UI Thread. but its freezing my UI
so i changed that into Background worker thread like

C#
_MyWoker = new BackgroundWorker();
_MyWoker.DoWork += new DoWorkEventHandler(_MyWoker_DoWork);
_MyWoker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_MyWoker_RunWorkerCompleted);


_MyWoker_DoWork takes my LoadDetails(); function this contain the UI controls statement

how can own UI thread From BackGroundWorker thread?
Current Exception:
<b>The calling thread cannot access this object because a different thread owns it</b>

Thanks in advance!
Posted

You can only access UI controls from the UI thread - the main thread. If you try from any other thread, you will get the exception you have seen.

There are two ways to get round it:
1) Use Control.Invoke to move the action back to the UI thread.
2) Do the control update in the ProgressChanged event, which is handled on the UI thread.
 
Share this answer
 
Certain cross-threads calls are not allowed, by a number of reasons. You can easily delegate some methods to UI thread. This way, you can create an object in UI thread, and call all its methods in UI thread, but the calls are triggered in some other thread. This is the case when you call methods/properties related to the currently running UI — all such calls should be done in UI thread only. you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

By the way, if you needed to delegate some calls to non-UI thread, you would need to program that thread in a special way. You can understand how it works if you see my article: Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^].

This small article is complete with full source code and detailed usage sample. Note that starting with .NET v.4.0, you could also use System.Collections.Concurrent.BlockingCollection<T>:
http://msdn.microsoft.com/en-us/library/dd267312.aspx[^].

See also the alternative to my article referenced above. The benefit of my article is that I explain how it works under the hood and the usage, but Microsoft class is better in performance.

—SA
 
Share this answer
 
v2

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