Loading Window and Updating UI - wpf

i have drawing app i want when i load saved project to show loading window
this is common task but i have problem to implement it correctly
i have tried many ways but it didn't work
note that
1- i want to load file and update the UI (Canvas )
2- i have many Canvases and i Encoder it to Bitmaps but it takes long time i want to Encode it in another thread but as you know i can't modify any object in UI Thread in another thread
i used BackgroundWorker and threads with dispatcher but i Got nothing
thank you

What objects are you loading on the background thread? If they're Freezable (such as BitmapFrame) then you can Freeze() them after loading, thus making them accessible from any thread.

Related

Can a thread be accessed from two forms in a Windows forms application

I wish to run a thread to update the Image in the picturebox . The image is streamed form the camera.
I require to stream images to two pictureboxes in two different forms, but one at a time.
Is it possible to create a single thread which can be accessed by both forms.
I think a backgroundworker would be appropriate. But how do I update the images in the picturebox of the respective forms?
I am using VC++ CLI/CLR
A Thread is an object which represent an independent path of execution (often run in parallel to another). I'm not really sure what you mean by "calling" a Thread but you can instantiate separate threads and run methods on them. Then between the Threads you have created you can use some kind of synchronisation such as Monitors, Mutexes and Events and a shared resource (being careful with cross-thread access).
For your problem I would be more tempted to use some kind of subscription pattern where the class which receives the images from the camera can update any observers of the camera. You may want an interface called ICameraObeserver with a method such as ReceiveImage, then any class could register with your camera class via some kind of method:
public void Register(ICameraObserver ico)
Then when the camera receives a new image, it can iterate through any subscribers of type ICameraObserver and call ReceiveImage passing the image it just received.
Just an idea. Be careful with updating the UI if you have multiple threads running - there is lots of information on this.
What I think you wanna do is this: when creating the new form, send to the constructer the first form as an object , then , and make a setter/ getter or just make the thread public, then you can "access" it from both forms as you requested.

Creating a WPF element in another Thread

I'm able to run 2 or more WPF windows on different thread.
The problem is that now my application in splitted in many windows.
What I really want is have a main window containg a grid in which every cell contains an element managed by a different thread.
Is it possible to create a UIElement/Component managed by a thread that is not the one which manage the parent/ containing window?
or
Is it possible to encapsulate a window that runs on a different thread in some frame/UIElement?
Thanks
Is it possible to use a MediaElement to project a window into a Panel?
"What I really want is have a main window containg a grid in which every cell contains an element managed by a different thread."
One way to go about this would be to create your elements normally in the cell. Create a regular class ViewModel that doesn't touch the UI but runs on it's own thread. This class is the brains behind what you're actually trying to DO with in your cells, not what you're trying to SHOW in your cells. This ViewModel class should implement INotifyPropertyChanged when it's data is has been updated. In your MainWindow.cs file you can set your cell elements' DataContext to these ViewModels. Lastly, in your XAML you can Bind things you're trying to show with the Properties in your ViewModel.
I know I breezed over a lot of details, but it's a starting point. Lots of help to be had around here if you need any.
It's not possible in WPF and even if it was it would have been a bad idea:
It's not possible in WPF because WPF element can only be used by the thread that created them, if you add a child element from another thread they wouldn't be able to communicate.
In pure Win32 it is possible - but it joins the two threads message queues so the threads are no longer independent (so even if you find a hack that makes it work with WPF it still doesn't help you)
Any thread that has UI and performs a long running task can hung the entire system - so it's impotent to never perform any long running task in a UI thread - instead run the long task in a background thread
because you have to keep the UI thread responsive -> it should never be busy for a noticeable length of time -> it can handle all your windows because it's not too busy.

Creating WPF components in background thread

Im working on a reporting system, a series of DocumentPage are to be created through a DocumentPaginator. These documents include a number of WPF components that are to be instantiated so the paginator includes the correct things when later sent to the XpsDocumentWriter (which in turn is sent to the actual printer).
My problem now is that the DocumentPage instances take quite a while to create (enough for Windows to mark the application as frozen) so I tried to create them in a background thread, which is problematic since WPF expects the attributes on them to be set from the GUI thread. I would also like to have a progress bar showing up, indicating how many pages have been created so far. Thus, it looks like Im trying to get two things to happen in parallell on the GUI.
The problem is hard to explain and Im really not sure how to tackle it. In short:
Create a series of DocumentPage's.
These include WPF components
These are to be created on a background thread, or use some other trick so the application isnt frozen.
After each page is created, a WPF ProgressBar should be updated.
If there is no decent way to do this, alternate solutions and approaches are more than welcome.
You should be able to run the paginator in a background thread as long as the thread is STA.
After you've set up your thread, try this prior to running it.
thread.SetApartmentState(ApartmentState.STA);
If you really must be on the GUI thread, then check out the Freezable class, as you might have to move the objects from your background thread to the GUI thread.
If the portions that require the UI thread are relatively small, you can use the Dispatcher to perform those operations without blocking the UI. There's overhead associated with this, but it may allow the bulk of the calculations to occur in the background and will interleave the work on the UI thread with other UI tasks. You can update the progress bar with the Dispatcher as well.
My guess is that everything that is time-consuming to create is within your Visual. If so, there is an easy solution: Don't create actual DocumentPage objects and their associated Visuals until DocumentPaginator.GetPage() is called.
As long as the code that consumes your document only requests one or two pages at a time there will be no performance bottleneck.
If you're printing to the printer or to a file, everything can be done on a background thread, but if you're displaying onscreen you only need to display a few DocumentPages at a time anyway. In either case you won't get any UI lockups.
The worst case scenario would be an app that displays pages in a thumbnail view. In this case, I would:
The thumbnail view would bind its ItemsSource to a "RealizedPages" collection which initially is filled with dummy pages
Whenever a dummy page is measured, it queues a dispatcher operation at DispatcherPriority.Background to call DocumentPaginator.GetPage() and then replace the dummy page in the RealizedPages collection with the real page.
If there are performance concerns even with realizing a single page because of the number of separate items, this same general approach can be used within whatever ItemsControl on the page has the large number of items.
One more note: The XPS printing system doesn't ever process more than one DocumentPage at a time, so if you know that's your client you can actually just keep returning the same DocumentPage over and over again with appropriate modifications.
Elaborating further on Ray Burns' answer: Couldn't you have your dataprocessing done in a class on a background thread and then databind the DocumentPage's properties to this class when the processing is done?
A little late to the game on this one, but I just worked out a solution to this so I thought I would share. In order to display the UI elements they have to be created on the UI thread on which they will be displayed. Since the long running task is on the UI thread, it will prevent a progress bar from updating. To get around this, I created the progress bar on a new UI thread and created the pages on the main UI thread.
Thread t = new Thread(() =>
{
ProgressDialog pd = new ProgressDialog(context);
pd.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
pd.Show();
System.Windows.Threading.Dispatcher.Run();
});
t.SetApartmentState(ApartmentState.STA);
t.IsBackground = true;
t.Start();
Action(); //we need to execute the action on the main thread so that UI elements created by the action can later be displayed in the main UI
'ProgressDialog' was my own WPF window for displaying progress information.
'context' holds the progress data for my progress dialog. It includes a cancelled property so that I can abort the action running on the main thread. It also includes a complete property so the progress dialog can close when the Action has finished.
'Action' is the method used to create all the UI elements. It monitors the context for the cancel flag and stops generating the UI elements if the flag is set. It sets the complete flag when it is done.
I don't remember the exact reason I had to set Thread 't' to an STA thread and IsBackground to true, but I am pretty sure it won't work without them.

WPF UI Thread Status

I have a wpf application that takes ~30 seconds to create a map/graphic. I have read there is no easy way to tie into the UI rendering thread to get a progress update. So I was going to use a counter on a value converter which colors my map but that is also on the UI Thread, so my question is has anyone found any slick methods of working with the rendering thread yet?
Thanks.
You could create your map/graphic in a BackgroundWorker which allows you to call ReportProgress in your function, where you can set your percentage of completion and raise the ProgressChanged event to update your UI.
When you say UI rendering thread, you mean that hidden rendering thread from WPF internals or UI thread?
In any case, having a separate thread that builds your map and notifies UI about progress doesn't help you?
im not sure if this is what you are looking for.
I use something similar to the code below to load in around 300 images( about 200 mb ) and have no UI slow down at all. (the user can see each image being loaded in, I just keep an empty placeholder image up till the final image is loaded)
The images are loaded in a background thread, and then the function is called to actually put them into the WPF scene.
here is a simple example using a textbox. You can call this function from any thread and it will work out if it needs to change the to the GUI thread. (for my project of course i am doing it with bitmaps, not a textbox ).
delegate void UpdateUIThreadDelegate(String str);
public void DisplayString(String strMessage)
{
if (this.InvokeRequired)
{
UpdateUIThreadDelegate updateDelegate = DisplayString;
this.BeginInvoke(updateDelegate, strMessage);
return;
}
myTextBox.Text = strMessage;
}
Cheers
Anton
If you use binding to tie your UI with a datasource which can take long time to return, you can set 'IsAsync=True' on your binding so that the binding become asynchronous.
If you want to display some other datas (even an animation I guess) during the time your datasource is loading, you can use a PriorityBinding
HTH
Riana

Separate UI thread for details view using WinForms

Our app's master/details view uses a datagridview as the master, and a custom control as the details view. The details view takes a long time to compute and render, making cursoring up/down the master view painfully slow.
Therefore, we'd like the details view to run asynchronously (in a separate UI thread) with change notifications from the master.
Creating a form in a separate thread is relatively straightforward, as Application.Run takes a form parameter.
Is there a way to run a winforms control on a separate thread? I'm aware that native windows in different threads can have a parent/child relationship, just not sure how to set that up using winforms.
TIA,
Updating the UI from a Secondary Thread
http://msdn.microsoft.com/en-us/magazine/cc188732.aspx
Intuitively, you also ought to be able to accomplish the same thing by using a BackgroundWorker. The BackgroundWorker is designed to update UI things like progress bars while executing stuff in the background, and it can be cancelled during its operation.
Is the slowdown caused by the loading of the data, or the population of the UI itself?
Most of the time it's the former, so if that's the case, then the logic that does the data loading should be abstracted into a different thread. The UI code can live in the main thread since updates are quick. You could use either a Thread or a BackgroundWorker in this situation. The key is to separate your data loading from your GUI population.
If you are firing off the update of the detail view in code, you can greatly improve the usability by sleeping 500ms between the time that the user selects the master record, and the time you update the detail view.
This gives the user 1/2 second to scroll to the next record without the details view updating at all.
If you're taking a speed hit during rendering, you should consider suspending layout until the form has completed updating, and then refresh the visible display once at the end.
this.SuspendLayout();
// Do control stuff here
this.ResumeLayout();
If that doesn't help, try this:
[DllImport("user32.dll")]
public static extern bool LockWindowUpdate(IntPtr hWndLock);
//
LockWindowUpdate(this.Handle);
// Do control stuff here
this.Refresh(); //Forces a synchronous redraw of all controls
LockWindowUpdate(IntPtr.Zero);
http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/8a5e5188-2985-4baf-9a0e-b72064ce5aeb

Resources