WPF/threading: Dispatcher static vs Dispatcher on a control? - c#

I'm a bit confused in terms of the dispatcher. Say I'm on a background thread doing some kind of long operation. I'd like to update the ui thread I understand I do this through the dispatcher. My question is, do i call the dispatcher statically like: Dispatcher.BeginInvoke(mywork) ... Or on the control i want to update: mytextbox.Dispatcher.BeginInvoke(mywork)

It's worth noting that calling Dispatcher.BeginInvoke isn't a static call: it's an implicit this.Dispatcher.BeginInvoke. If you can use this call, you're likely writing your code from within a control or window already. In that case, you're probably safe to call either since most of the time there will be one UI thread per application.
The actual static call would be Dispatcher.CurrentDispatcher.BeginInvoke, which is not something you want to call (see my comment on Hasan Khan's answer for why).
EDIT: Calling Application.Current.Dispatcher is not a bad thing. (And, for clarity, it's an instance property, not a static - being called on a static/singleton instance of Application.) This property will return the Dispatcher for the thread that the app was created with, and typically that's the thread that the UI is created on aswell - so Application.Current.Dispatcher returns the same Dispatcher as myWindow.Dispatcher would.
The static call Dispatcher.CurrentDispatcher (that I warned against) returns a Dispatcher for the thread you call it from. If you call it from a background thread, you'll get a new Dispatcher created especially for that thread - which often isn't what's wanted.

First I think it is important to understand, that the Dispatcher is not designed to handle big background operations. It is designed to queue work on the UI thread of an object. Here is a worthwhile MSDN article about the .NET threading model and Dispatcher:
Threading Model, Overview and the Dispatcher
Saying that the standard way of implementing the Dispatcher.BeginInvoke method would be to call it on the control:
startStopButton.Dispatcher.BeginInvoke(
DispatcherPriority.Normal, new NextPrimeDelegate(CheckNextNumber)
);
Hope that helps!

While in most cases using either DispatcherObject.Dispatcher (all dependency objects and controls inherit from DispatcherObject, among others) or Application.Current.Dispatcher is the right thing to do, as there's usually only one UI thread, there can be multiple UI threads and different windows can use different dispatchers. In that case, it's important to update the control using its dispatcher. It's stored in in its Dispatcher property (inherited from DispatcherObject), any other control in this window and the window itself.

Related

Attach FixedDocument created in another thread [duplicate]

A common exception one can get when working with multiple threads in WPF is:
The calling thread cannot access this object because a different thread owns it
What are the options to deal with this properly?
Depending on the situation there are various options:
Accessing a control from another thread
e.g. updating a TextBlock with progress information.
Data Binding:
In this case the easiest thing you can do is avoiding the direct interaction with the control. You can just bind the property you want to access or modify to an object whose class implements INotifyPropertyChanged and then set the property on that object instead. The framework will handle the rest for you. (In general you rarely should need to interact with UI-elements directly, you can almost always bind the respective properties and work with the binding source instead; one case where direct control access may be necessary is control authoring.)
There are some cases where data binding alone is not enough, for example when trying to modify a bound ObservableCollection<T>, for this you need...
Dispatching:
You can dispatch your accessing code to the thread owning the object, this can be done by calling Invoke or BeginInvoke on the Dispatcher owning the object being accessed (getting this Dispatcher is possible on another thread).
e.g.
new Thread(ThisThreadStart).Start();
void ThisThreadStart()
{
textBlock.Dispatcher.Invoke(new Action(() => textBlock.Text = "Test"));
}
If it is not clear on which thread a method is executed you can use Dispatcher.CheckAccess to either dispatch or execute an action directly.
e.g.
void Update()
{
Action action = () => myTextBlock.Text = "Test";
var dispatcher = myTextBlock.Dispatcher;
if (dispatcher.CheckAccess())
action();
else
dispatcher.Invoke(action);
}
If an object is not a DispatcherObject and you still need the associated Dispatcher you can use Dispatcher.CurrentDispatcher in the thread creating the object (so doing this in the method being executed by a thread will not do you any good). For convenience as you usually create objects on the application's main UI thread; you can get that thread's Dispatcher from anywhere using Application.Current.Dispatcher.
Special cases:
BackgroundWorker
Move any control access to ProgressChanged as it occurs on the thread that created the instance (which should of course be the UI-thread)
Timers
In WPF you can use the DispatcherTimer for convenience, it does the dispatching for you so any code in Tick is invoked on the associated dispatcher. If you can delegate the dispatching to the data binding system you of course can use a normal timer as well.
You can read more about how the Dispatcher queue works and WPF threading in general on MSDN.
Accessing an object created on another thread
e.g. loading an image in the background.
If the object in question is not Freezable you should in general simply avoid creating it on another thread or restricting access to the creating thread. If it is Freezable you just need to call Freeze to make it accessible to other threads.
Accessing a data object from another thread
That is, the type whose instance is being updated is user-code. If an exception is thrown this situation probably came about by someone using DependencyObject as base type for a data class.
This situation is the same as accessing a control and the same approaches can be applied but usually it should be avoided in the first place. Granted, this allows for simple property change notifications via dependency properties and those properties can also be bound but often enough this is just not worth giving up thread-independency. You can get change notifications from INotifyPropertyChanged and the binding system in WPF is inherently asymmetrical, there always is a property that is bound (target) and something that is the source for this binding. Usually the UI is the target and the data is the source, meaning that only UI components should need dependency properties.
That would be several hundred lines of code, for something I "figured out".
But the summary is:
App_OnStartup
generate a background thread
in the callback,
Call
Application.Current.MainWindow.Dispatcher.CheckAccess() - gets the exception
Application.Current.Dispatcher.CheckAccess() does not
I have a udp listener object that communicates through events where the method/callbacks are +='ed in my mainWindow wpf .cs file.
The event handler functions are called with parameters, one being the message I want displayed in a listbox in the mainWindow.cs
Using the information in this thread by H.B. above;
I have added, tested and handled the crossthread in wpf in my eventhandler callback using the following code, but I use a real message not a hard coded one:
listBox1.Dispatcher.Invoke(new Action(() => listBox1.Items.Add("MessageHere")));
UPDATE:
This is better because you can put more things in the anonymous function.
listBox1.Dispatcher.Invoke((Action)delegate
{
listBox1.Items.Add(e.ReaderMessage);
});

Automatic Invoking for cross-thread actions

is there any solution for this scenario:
I do some time-consuming things on a new Thread (using Tasks). In this thread I want to update UI elements (text) so that the user knows what happens. This should happen at real-time, not only when a Task finished.
I always must explicitly call Dispatcher.Invoke() (it's the UI-Thread dispatcher) if I want to change something. Is there a way to run something asynchronously without having to invoke explicitly? I found a solution using the TaskFactory and specifying a TaskScheduler. But this locks the UI when UI-calls are made.
Is there a way to do this, without locking the UI?
EDIT: Because of some slight misunderstandings this edit.
I want that once I call something like
uiControl.Text = "Test 123";
on the worker-thread to be automatically invoked on the UI-Thread if needed. So in this case it's needed, but I want to get rid of all these Invoke-calls. So if there is a nifty solution it would be great. Otherwise I have to use explicit invokes, not nice but ok.
PostSharp has this implemented as a method level aspect. What it means in terms of implementation is that you decorate a method with [DispatchedMethod] attribute and it will be dispatched to the UI thread every time it is called (by any thread). Take a look here for more details:
http://www.postsharp.net/aspects/examples/multithreading
http://www.postsharp.net/threading/thread-dispatching
http://doc.postsharp.net/##T_PostSharp_Patterns_Threading_DispatchedAttribute
You can do the operation on main thread and just call Application.DoEvents() from time to time in order to process UI events ...
Note that this only works for winforms so probably not a correct answer.
HighCore suggested this as a better answer https://stackoverflow.com/a/21884638/643085

Is calling Dispatcher.CheckAccess() good form in Silverlight?

I wonder if the following code buys any performance gains:
if (Deployment.Current.Dispatcher.CheckAccess())
{
DoUIWork();
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
DoUIWork());
}
Is the Dispatcher smart enough to short circuit a dispatch to the UI thread if its unnecessary?
I couldn't say whether the dispatcher does anything expensive when dispatching from the UI thread to itself, compared with the check. But BeginInvoke from the UI thread may behave differently from executing the operation directly, as it's at least put on the queue rather than invoked immediately. You could tell the difference between this and removing the conditional statement if you had code directly afterwards.
Certainly worth being aware of the control flow, enough to know if the difference doesn't matter.
If it is anything like standard Windows SynchronizationContext (and it probably is) then the two options are not the same. BeginInvoke will basicaly queue up the method to be executed by the dispatcher message pump after the current execution of any existing message has been processed.
In your example the two options be the same if you were to use Invoke instead of BeginInvoke.

How to Make Sure UI is Responsive Using BackgroundWorker

Is BackgroundWorker in c# Thread Safe?
The reason I ask this is because I get a
Controls created on one thread cannot
be parented to a control on a
different thread
exception with it. This is my DoWork event code:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var openFile = document.Open(MyFileName);
e.Result = openFile;
}
where document is an UI control that is initialized when the parent form is created. During Open method various properties in document will be filled.
I tried to change the code to invoke, yet the same problem persists. i.e,
document.GetType().GetMethod("Open)".Invoke(document, new object[]{MyFileName})
will yield the same error as the above.
Any idea how to manipulate the document control? In other words, how to make the above code work?
Edit: It was suggested that I use Control.Invoke, but it still didn't work ( both of the threads hanged). This is the code I tried:
private delegate bool OpenFile(string filePath);
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
OpenFile oF = new OpenFile(document.Open);
var openFile = Invoke(oF, MyFileName); // it doesn't really matter whether I use BeginInvoke or Invoke, or other Control.Invoke, the end result is the same. Both the main thread hosting the document and the thread that launches the UI hanged.
e.Result = openFile;
}
It isn't the thread that's the problem it's the fact that it's trying to call a method on a UI control. In both WPF and WinForms controls can only be called on the UI thread (of which there is typically one). You don't say which you are using but you need to call the Control.Invoke method for WinForms or Dispatcher.Invoke for WPF.
The Invoke() reflection method you show will actually invoke the method on the current thread.
You can either invoke as Mehrdad Afshari suggested, or you can make use of the bgw's progress event which comes back on the UI thread. Or the work completed event which also comes back on the UI thread. The difference between the two is WorkCompleted is fired only once at the end. Progress is fired by you from DoWork.
While it's unclear to me what you exactly mean by thread-safety of a BackgroundWorker, the problem is not that object; Windows Forms controls are designed to be manipulated on a single thread (the UI thread). You should not manipulate Windows Forms objects on different threads. You can invoke actions in the UI thread from other threads by using the Control.Invoke method (the Invoke method you are currently using is provided by reflection and is totally unrelated to this problem):
Invoke(new Action(MethodToRunInUIThread));
void MethodToRunInUIThread() {
// do stuff here.
}
By the way, it doesn't make sense to use a background worker if all you are doing is manipulating UI objects.
If that functionality of the UI Control takes that long to execute, there may not be much you can do. "Freezing" occurs when a long-running operation happens on the UI thread, and if that function of the control was not specifically made thread-safe, it must be run on the main thread.
Normally, you'd want to separate the "document" functionality away from the control that displays it. This way, your document could be loaded on a separate, independent thread and be displayed later when ready. Otherwise, the control itself would have to implement a multi-threaded load routine to slow loading freezes.
Since you've specified this is a third party control in your comments, you may be out of luck here.
BackgroundWorker is a thread based structure. The thread-safety matter is about functions when doing simultaneous tasks. Maybe what you ask for is about winforms controls which are accessed through a unique thread, that of the user interface thread.
You need to use Control.BeginInvoke() in DoWork. This executes the delegate asynchronously and so will ensure the calling thread will not "hang".
Control.Invoke() will execute the delegate on the other thread also, but will cause the calling thread to wait for it to complete.
Generally in Windows Forms you are better off using Control.BeginInvoke() wherever possible to help avoid deadlocking between threads that can occur when one thread waits for another, as with Control.Invoke().
If the "document" object inherits from System.Windows.Forms.Control, you can simply call document.BeginInvoke(myDelegate).
However if it is actually some other component that encapsulates GUI controls, it may expose some way to call BeginInvoke. Check the documentation (if any). If there is no such ability, then unfortunately it is probably just not designed to support multi-threaded applications.
It looks like you are confused about the various Invoke/BeginInvoke types (understandable). This earlier question: What is the difference between Invoke and BeginInvoke? and Jon Skeets answer should help clarify things.
#Graviton, a related task with an answer is found here. The person was using BackgroundWorker to update a textbox, same concept applies (yours is only a single worker thread).

How to start a UI thread in C#

I know I can start a new worker thread from with .NET. But how do I start a new UI thread (like in MFC)?
I don't mind if the solution is restricted to Windows boxes only; I also would like the solution to be purely .NET - no p/invokes to CreateThread, etc.
Any input appreciated.
Use Application.Run - it starts a message loop in the current thread. There are overloads to take a form to start with, or an application context, or neither. (If you want to do this for a new thread, you need to create the thread and start it in the normal way, and make it call Application.Run.)
If you are interested in using WPF, check out MSDN's article WPF's Threading Model, in particular the "Multiple Windows, Multiple Threads" section. It details what you need to do to create a new Dispatcher and show a window on a new thread.
If you're looking to create a new thread that is capable of creating and dealing with Window handles, then you can use the SetApartmentState function on the Thread object and set it to STA. You'll also likely need to call Application.Run inside the method for this thread in order to create your message loop. However, bear in mind that you're subject to the same cross-threading no-no's that you have in any other thread (ie, you can only interact with the handle for a control on the thread inside which it was created), so you can't do anything on your other UI thread without switching contexts.
Also you can do this:
delegate void MyProcHandler(object param1, object param2);
MyForm.Invoke
(
new MyProcHandler(delegate(object param1, object param2)
{
// some code
}),
null,
null
);

Categories

Resources