When is a UI Element assigned to thread - c#

I know I have seen an article or SO on this before, but cannot seem to find it now. I ran into a problem helping a coworker write a test that was checking UI actions that were occurring across multiple threads (I realize the problems here...that is not what I want to focus on at the moment :)). The code looks similar to this kind of pseudocode:
[RequiresSTA]
Test
{
var tb = new Textbox();
tb.DoSomethingAsyncAndThenUpdateTB() //This is done via tb.SetValue being called
}
...
DoSomethingAsyncAndThenUpdateTB()
{
var bw = new BackgroundWorker();
bw.DoWork += ...Do Stuff...
bw.RunWorkerCompleted += { tb.Text = "foo";}
}
The problem I am running into is that the OnComplete is throwing a cross thread exception. However, everything should have been created on the STA thread. I BELIEVE the problem is that UI elements get attached to their thread not on creation, but at a later point....and my textbox ends up attaching to a thread that isn't the STA? Or maybe the backgroundworker?
The question:
When does a UI element actually get attached to a thread?

So first off, there isn't just one STA thread. Any thread can be created as an STA thread when it's created. The UI thread needs to be an STA thread, but not all STA threads are UI threads.
Next, you have the issue that BackgroundWorker needs to have some way of knowing what the UI thread is. It's not magic that it's able to marshal certain events to the UI thread. What it does is it looks at the value of SynchronizationContext.Current in its constructor. It then captures the value of that context, and uses it later as it's definition of the context to post all non-work events to. If you create the BGW outside of the UI thread then it's not able to marshal back to the UI thread later.
If you have an STA thread that you are using as your UI thread, but you haven't set a value of SynchronizationContext.Current, then the BGW won't be able to do its thing.
As for the question of:
When does a UI element actually get attached to a thread?
In its constructor.

Each ui element implements DependencyObject, which implements abstract class DispatcherObject.. When DispatcherObject is created it assigns current dispatcher to the DispatcherObject..
Later on, whenever you access any property of the UI element, there is a validation that checks if you are accessing it from UI thread.
This si done in VerifyAccess
/// <summary>Enforces that the calling thread has access to this <see cref="T:System.Windows.Threading.DispatcherObject" />.</summary>
/// <exception cref="T:System.InvalidOperationException">the calling thread does not have access to this <see cref="T:System.Windows.Threading.DispatcherObject" />.</exception>
[EditorBrowsable(EditorBrowsableState.Never)]
public void VerifyAccess()
{
Dispatcher dispatcher = this._dispatcher;
if (dispatcher != null)
{
dispatcher.VerifyAccess();
}
}
If a calling thread is not the one associated with dispatcher, then exception is thrown
public void VerifyAccess()
{
if (!this.CheckAccess())
{
throw new InvalidOperationException(SR.Get("VerifyAccess"));
}
}
This is called Thread Affinity

Related

STA call from MTA

I am just starting to deal with STA/MTA issues, so apologies for the simplicity of the question. I couldn't find an answer I could actually understand at the bottom of the ladder here.
I am writing a plugin for another piece of software, and come to a point in a worker thread that I need to create some UI elements. I understand that I cannot do that from inside the worker thread since it is not an STA thread, and that I need to get back to the Main (or just another?) STA thread to create the UI elements. Some clarifications would help greatly.
Do all STA threads have the same 'rights', i.e. if the main thread is STA and creates a Window, adds some UI elements to it. Then spawns off another STA thread, and that second thread likewise creates some UI elements, are they doing it in the same 'space' (poor word choice, but I don't know what else to use) and can access each other's UI elements without causing death and destruction? Or do I need to explicitly jump back to the Main/Original STA thread and ONLY ever create UI elements from THAT (not just ANY) STA thread?
If that is the case (only 1 STA thread is allowed to make UI elements) how do I do that correctly? I have seen many posts that related to this but for some reason I can't quite catch what's going on, and would love a REAL simple answer.
Please no 'Here's a cool slick way of doing...' I just need the simple way of at the point of execution where I need some UI elements jumping back over to the main STA thread if that's what's necessary.
If it is not necessary, then I will just make that worker thread an STA thread and continue on my way, is that fair? Or am I courting disaster?
if the main thread is STA and creates a Window, adds some UI elements to it. Then spawns off another STA thread, and that second thread likewise creates some UI elements, are they doing it in the same 'space' [snip...] and can access each other's UI elements without causing death and destruction?
If Thread A and B are both STA, then they can each create and update their own UI elements, but not eachothers. Any other threads that want to affect the UI have to use one of the BeginInvoke style methods to ask the appropriate thread to do the update.
If it is not necessary, then I will just make that worker thread an STA thread and continue on my way, is that fair? Or am I courting disaster?
You may not be able to make the worker thread an STA thread if it's been set to MTA and initialized. You may have to make a new thread.
How do you do it? It seems like you want to use WPF (System.Windows.*) for your UI - so If the app that you are "plugging into" is also using WPF, you should be able to access it and re use it's UI thread. If not, you can make a new thread, and create a new Application on it and call Run. This should set up a dispatcher for you.
Something like this (pseudo code sort-of copied from some working code I have elsewhere)
Dispatcher dispatcher = null; // we 'get to' the UI thread via the dispatcher
if(Application.Current) { // re use an existing application's UI thread
dispatcher = Application.Current.Dispatcher;
} else {
var threadReadyEvent = new ManualResetEvent(false);
var uiThread = new Thread(() => {
Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
var application = new Application();
application.Startup += (sender, args) => {
dispatcher = application.Dispatcher;
threadReadyEvent.Set();
};
// apps have to have a "main window" - but we don't want one, so make a stub
var stubWindow = new Window {
Width = 1, Height = 1,
ShowInTaskbar = false, AllowsTransparency = true,
Background = Brushes.Transparent, WindowStyle = WindowStyle.None
};
application.Run(stubWindow);
}){ IsBackground = true };
uiThread.Start();
threadReadyEvent.WaitOne();
threadReadyEvent.Dispose();
}
dispatcher.Invoke(() => {
// ask the UI thread to do something and block until it finishes
});
dispatcher.BeginInvoke(() => {
// ask the UI thread to do something asynchronously
});
and so forth
If a thread creates a control. Only this specific thread can interact with it, even if there are other STA threads.
In WinForms you would invoke a method on the control: Control.Invoke.In WPF you have the dispatcher to do it: Dispatcher.Invoke.
WinForms:
form1.Invoke(/* a delegate for your operation */)
WPF:
window1.Dispatcher.Invoke(/* a delegate for your operation */)
What you do is instead of changing an object in a "single apartment" you ask (invoke) the STA thread in control of it to do it (the delegate you invoke) for you. You also have BeginInvoke for doing it asynchronously.

Invoke(Delegate)

Can anybody please explain this statement written on this link
Invoke(Delegate):
Executes the specified delegate on the thread that owns the control's underlying window handle.
Can anybody explain what this means (especially the bold one) I am not able to get it clearly
The answer to this question lies in how C# Controls work
Controls in Windows Forms are bound to a specific thread and are not
thread safe. Therefore, if you are calling a control's method from a
different thread, you must use one of the control's invoke methods to
marshal the call to the proper thread. This property can be used to
determine if you must call an invoke method, which can be useful if
you do not know what thread owns a control.
From Control.InvokeRequired
Effectively, what Invoke does is ensure that the code you are calling occurs on the thread that the control "lives on" effectively preventing cross threaded exceptions.
From a historical perspective, in .Net 1.1, this was actually allowed. What it meant is that you could try and execute code on the "GUI" thread from any background thread and this would mostly work. Sometimes it would just cause your app to exit because you were effectively interrupting the GUI thread while it was doing something else. This is the Cross Threaded Exception - imagine trying to update a TextBox while the GUI is painting something else.
Which action takes priority?
Is it even possible for both to happen at once?
What happens to all of the other commands the GUI needs to run?
Effectively, you are interrupting a queue, which can have lots of unforeseen consequences. Invoke is effectively the "polite" way of getting what you want to do into that queue, and this rule was enforced from .Net 2.0 onward via a thrown InvalidOperationException.
To understand what is actually going on behind the scenes, and what is meant by "GUI Thread", it's useful to understand what a Message Pump or Message Loop is.
This is actually already answered in the question "What is a Message Pump" and is recommended reading for understanding the actual mechanism that you are tying into when interacting with controls.
Other reading you may find useful includes:
What's up with Begin Invoke
One of the cardinal rules of Windows GUI programming is that only the
thread that created a control can access and/or modify its contents
(except for a few documented exceptions). Try doing it from any other
thread and you'll get unpredictable behavior ranging from deadlock, to
exceptions to a half updated UI. The right way then to update a
control from another thread is to post an appropriate message to the
application message queue. When the message pump gets around to
executing that message, the control will get updated, on the same
thread that created it (remember, the message pump runs on the main
thread).
and, for a more code heavy overview with a representative sample:
Invalid Cross-thread Operations
// the canonical form (C# consumer)
public delegate void ControlStringConsumer(Control control, string text); // defines a delegate type
public void SetText(Control control, string text) {
if (control.InvokeRequired) {
control.Invoke(new ControlStringConsumer(SetText), new object[]{control, text}); // invoking itself
} else {
control.Text=text; // the "functional part", executing only on the main thread
}
}
Once you have an appreciation for InvokeRequired, you may wish to consider using an extension method for wrapping these calls up. This is ably covered in the Stack Overflow question Cleaning Up Code Littered with Invoke Required.
There is also a further write up of what happened historically that may be of interest.
A control or window object in Windows Forms is just a wrapper around a Win32 window identified by a handle (sometimes called HWND). Most things you do with the control will eventually result in a Win32 API call that uses this handle. The handle is owned by the thread that created it (typically the main thread), and shouldn't be manipulated by another thread. If for some reason you need to do something with the control from another thread, you can use Invoke to ask the main thread to do it on your behalf.
For instance, if you want to change the text of a label from a worker thread, you can do something like this:
theLabel.Invoke(new Action(() => theLabel.Text = "hello world from worker thread!"));
If you want to modify a control it must be done in the thread in which the control was created. This Invoke method allows you to execute methods in the associated thread (the thread that owns the control's underlying window handle).
In below sample thread1 throws an exception because SetText1 is trying to modify textBox1.Text from another thread. But in thread2, Action in SetText2 is executed in the thread in which the TextBox was created
private void btn_Click(object sender, EvenetArgs e)
{
var thread1 = new Thread(SetText1);
var thread2 = new Thread(SetText2);
thread1.Start();
thread2.Start();
}
private void SetText1()
{
textBox1.Text = "Test";
}
private void SetText2()
{
textBox1.Invoke(new Action(() => textBox1.Text = "Test"));
}
Invoke((MethodInvoker)delegate{ textBox1.Text = "Test"; });
In practical terms it means that the delegate is guaranteed to be invoked on the main thread. This is important because in the case of windows controls if you don't update their properties on the main thread then you either don't see the change, or the control raises an exception.
The pattern is:
void OnEvent(object sender, EventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(() => this.OnEvent(sender, e);
return;
}
// do stuff (now you know you are on the main thread)
}
this.Invoke(delegate) make sure that you are calling the delegate the argument to this.Invoke() on main thread/created thread.
I can say a Thumb rule don't access your form controls except from main thread.
May be the following lines make sense for using Invoke()
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
There are situations though you create a Threadpool thread(i.e worker thread) it will run on main thread. It won't create a new thread coz main thread is available for processing further instructions. So First investigate whether the current running thread is main thread using this.InvokeRequired if returns true the current code is running on worker thread so call
this.Invoke(d, new object[] { text });
else directly update the UI control(Here you are guaranteed that you are running the code on main thread.)
It means that the delegate will run on the UI thread, even if you call that method from a background worker or thread-pool thread. UI elements have thread affinity - they only like talking directly to one thread: the UI thread. The UI thread is defined as the thread that created the control instance, and is therefore associated with the window handle. But all of that is an implementation detail.
The key point is: you would call this method from a worker thread so that you can access the UI (to change the value in a label, etc) - since you are not allowed to do that from any other thread than the UI thread.
Delegate are essentially inline Action's or Func<T>. You can declare a delegate outside the scope of a method which you are running or using a lambda expression(=>); because you run the delegate within a method, you run it on the thread which is being run for the current window/application which is the bit in bold.
Lambda example
int AddFiveToNumber(int number)
{
var d = (int i => i + 5);
d.Invoke(number);
}
It means that the delegate you pass is executed on the thread that created the Control object (which is the UI thread).
You need to call this method when your application is multi-threaded and you want do some UI operation from a thread other than the UI thread, because if you just try to call a method on a Control from a different thread you'll get a System.InvalidOperationException.

Cross-threading issue, BackgroundWorker and ReportProgress

I've got an [STAThread] main that contains something like this:
try
{
// Start the port enumerator.
Enumerator enumerator = new Enumerator();
// Display the main window and start everything going.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TopViewForm(ref enumerator));
}
catch (Exception)
{
}
The enumerator object itself contains a background worker thread. The background work is initialised like this:
MyBackgroundWorker = new BackgroundWorker();
MyBackgroundWorker.WorkerSupportsCancellation = true;
MyBackgroundWorker.WorkerReportsProgress = true;
MyBackgroundWorker.DoWork +=new DoWorkEventHandler(MyBackgroundWorker_DoWork);
MyBackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(MyBackgroundWorker_ProgressChanged);
MyBackgroundWorker.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(MyBackgroundWorker_RunWorkerCompleted);
MyBackgroundWorker.RunWorkerAsync();
Now, in order to report progress back to the main form (the instance of TopViewForm), the thread in Enumerator is calling ReportProgress with some appropriate user object. ReportProgress, I assume, will arrive in the form of ProgressChanged event and be executed on the main UI thread, which is the thread the Enumerator itself was created on (i.e. not the BackgroundWorker's thread).
Given that this is the case, how is it possible that I'm getting a cross-thread violation error when I try to set a node in a TreeView on the main process thread in response to an event from this object? The ProgressChanged categorically does not appear to be run on the main process thread, looking at the call stack.
I assume then, that Application.Run generates a new thread and runs the form with that? But the documentation says otherwise. Either I've made a dumb error or there's something I don't understand here.
Does anyone have any thoughts?
I believe that the progress changed event is running before Application.Run is first called. If you don't start the background worker from Main, but rather from inside one of the forms you will be sure that the message loop already exists when the background worker is created and starts reporting progress.
BackgroundWorker relies on a current SynchronizationContext being set in order to function. ProgressChanged event is implemented as SendOrPostCallback Delegate and as it stated in msdn documantation SendOrPostCallback represents a callback method that you want to execute when a message is to be dispatched to a synchronization context. Adding BackgroundWorker to a form in a Form designer sets SynchronizationContext properly. In your case BackgroundWorker has no SynchronizationContext assigned.

C# Threading and Forms: NotSupportedException - Use Control.Invoke?

I am trying to run an application with at least two threads: One form for the user interface and one or more worker threads. They are jointly reading/writing from a static class through a number of other classes.
This is why I am passing an instance of the worker class to the display form. I guess that is why it goes wrong for me:
public class CoCoon
{
private Screen displayForm;
private Worker worker;
public ThreadedApp()
{
worker = new Worker (1024);
displayForm = new Screen(worker);
}
public void Run()
{
//thread 1: display form
Thread screenThread = new Thread(() => Application.Run(displayForm));
//thread 2: background worker
Thread workerThread = new Thread(worker.Run) {IsBackground = true};
screenThread.Start();
Thread.Sleep(1000); //if I don't wait a while, I get an ObjectDisposedException!
workerThread.Start();
}
The threads and objects are initiated just fine, but as soon after the Form_Load method is has been handled, an error is thrown on the Application.Run(displayForm) line above. It is an NotSupportedException, with a remark that I should use Control.Invoke. But I am not sure I understand, because I am not letting threads other than the display form's use the controls on it.
I am new to threading. Can anyone help me on my way? Thanks!
PS: One detail - I am developing this for the Windows Mobile platform.
EDIT After popular request hereby the Stack Trace
at Microsoft.AGL.Common.MISC.HandleAr(PAL_ERROR ar)\r\n at
System.Windows.Forms.Control.get_Visible()\r\n at
System.Windows.Forms.Form._SetVisibleNotify(Boolean fVis)\r\n at
System.Windows.Forms.Control.set_Visible(Boolean value)\r\n at
System.Windows.Forms.Application.Run(Form fm)\r\n at
CoCoonWM6.CoCoon.<Run>b__1()\r\n
I recommend that you only have one UI thread, the main thread. You can use your other threads for background operations, but keep all UI stuff on the main thread.
The UI thread should be the only one calling Application.Run. WinForms has other requirements for the UI thread (such as being STA), and those are satisfied by the main thread. In theory, it may be possible for WinForms to support two UI threads, but it's certainly not easy.
I normally recommend other forms of synchronization when you need to update UI controls from a background thread - TaskScheduler or SynchronizationContext. On the mobile platform, unfortunately, your only option is Control.Invoke.
Check out the stack trace for the exception (and post it). You are almost certainly accessing some Control from the worker thread.
This is how you can modify access to a Control (in this example a Label) after you find where you are accessing controls from non-UI threads:
if (label13.InvokeRequired)
{
ChangeTextDelegate changeText = new ChangeTextDelegate(anyChangeTextMethod);
label13.Invoke(changeText, new object[] { newText });
}
else
{
label13.Text = newText;
}
Looks like you're trying to use GUI elements in the background thread. That would explain why you have to call Sleep (otherwise the form and its controls don't finish loading before you try to use them) as well as the Control.Invoke exception (you can't use GUI elements from a non-UI thread). See the docs for Control.Invoke for how you should use it.
Since you don't have BackgroundWorker and Px in the CF, you're indeed forced to use threads directly - though the ThreadPool would probably be better than instantiating new threads, most of the time.

Background Worker events

pseudo code:
form1
{
int i;
label1;
Add()
{
i++;
label1 = i.ToString(); //#ErrorLine
}
backgroundworker worker;
worker_DoWork()
{
FileGuard guard = new FileGuard();
guard.FileKilled += guard.KillH(Add);
guard.StarGuarding(); //there is system watcher inside
//this guard and some processing code
//that will fire event FileKilled();
}
}
Afer calling StartGuarding() worker will be compleated
But when there is event FileKilled fired I goth this error on line #ErrorLine
Cross-thread operation not valid: Control 'form1' accessed from a thread other than the thread it was created on.
This has nothing to do with the events themselves, but rather the fact that you are accessing UI controls from another thread. In Windows Forms, you are not allowed to interact with the UI from any other thread than the main UI thread.
You can use InvokeRequired to check whether you are on a thread that has no access to the UI, and then use Invoke to run code on the UI thread if required. It might look something like this:
private void DoStuffWithGUI()
{
if (InvokeRequired)
{
Action work = DoStuffWithGUI;
Invoke(work);
}
else
{
// Your normal logic
}
}
You can use the UI directly from ProgressChanged and RunWorkerCompletedEvents (because they are automatically marshalled to the UI thread). But all work you do within DoWork, (and therefore all events you might raise as part of the work) runs in a separate thread, and must be marshalled to the UI thread using Invoke. From MSDN for BackgroundWorker:
You must be careful not to manipulate
any user-interface objects in your
DoWork event handler. Instead,
communicate to the user interface
through the ProgressChanged and
RunWorkerCompleted events.
It's because a third thread is used when FileKilled is invoked by the system.
As for BackgroundWorker you should use events to handle GUI updates: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
You cannot access Windows Forms or WPF objects from anything other than the form they were created on, hence your issue.
Use a dispatcher to send the update back to your UI Thread.
If you can give detail on whether you're using WinForms or WPF we can give more information.
You cannot change modify the controls from a thread other than on which they were created. You need to use the InvokeRequired property and Invoke method to marshal the calls to the UI thread from the background thread.
private readonly _lockObject = new Object();
Add()
{
lock(_lockObject)
{
i++;
if(label1.InvokeRequired)
Invoke(new Action( () => label1 = i.ToString()));
else
label1 = i.ToString();
}
}
Note that the lock is not necessary to avoid this exception. It added to make the method thread safe.

Categories