I have a function in my silverlight app, that takes one or two seconds to finish. While executing this function, I want to show my "just loading" UC to the user:
private void ComboBoxGranularity_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
WaitScreenObject.Visibility = Visibility.Visible;
OperationThatTakesALittleTime();
WaitScreenObject.Visibility = Visibility.Collapsed;
}
Problem is, that Silverlight doesn't redraw while the function is executed, so my WaitScreen doesn't show up. I tried the trick from this question:
this.Visibility = Visibility.Visible;
but it didn't work. I wanted to avoid the Backgroundworker-Overhead, so is there any possibilty to make the WaitScreenObject visible?
Thanks in advance,
Frank
Your method runs on the UIThread since you mentioned that you are not using a background thread. The thread only redraws the screen when it is not busy with something else, since the queue is filled with the other instructions, and those are considered more important than a redraw.
I tried what Andrew suggested, but I could not find the InvalidateVisual() method on the UIElement. Maybe I was just being daft.
The reason why the linked example did not work for you, is because the other question just dealt with an element not being invalidated because it did not have focus. However, the UIThread was available for a refresh at that time.
I also tested the dispatcher.BeginInvoke() on a delegate, and it did not work either. I am afraid that from my point of view, you might just have to use a separate thread.
I could be wrong because I simulated my "work" by making the thread sleep instead, however, I cannot see what the difference will be.
Hope this helps.
Have you tried invalidating the visual for the root object to try convince it to redraw? (Havn't checked if it would work, just comes to mind as a hack)
Edit : InvaldiateVisual is the method in WPF on the UIelement, in Silverlight you use a diff call, such as InvalidateArrange
myCanvasRoot.InvalidateArrange();
Bit hacky but might convince it to perform the update of the screen.
Related
EDIT: Solved using this: http://reedcopsey.com/2011/11/28/launching-a-wpf-window-in-a-separate-thread-part-1/
In my project (.net/windows forms) I'm filling a DataGridView with a large DataTable. Filling can take up to 20 seconds, so I'd like an animated loading window. This animation freezes if the thread is busy, so I'll have to use a new thread either for the window or for filling the DataGridView.
I've tried using the BackgroundWorker to show the form, but it'll be a blank white window in the correct shape.
I've also tried using the BackgroundWorker to fill the DataGridView, but it'll throw an error saying the DataGridView is being accessed by a different thread than the one it has been created for. Since the DataGridView is being created in the designer class, I can't just create it in the new thread - plus that solution doesn't sound very elegant.
What's the best way for me to show a working animated form while filling the DataGridView?
Edit: The answer didn't solve the issue for me, so I've tried to break the code down to something that can be presented here. I didn't do it before because it didn't really seem relevant enough to work through some 1k lines of code. Might be something missing or some remnants from previous experiments in the code presented here. Please ignore bad naming of function, that's a legacy thing I'll fix once I got it working. Parts of the code are ancient.
I've made it run without errors, but the frmLoading still isn't animated (it is if I keep it alive while the working thread isn't busy, though).
namespace a
{
public partial class frmMain : DockContent, IPlugin
{
//...
private delegate void SafeCallDelegate(DataTable dt);
private Thread thread1 = null;
private frmLoading frmLoading = new frmLoading();
public frmMain()
{
//...
}
//...
private void FillDataGrid(DataTable dt)
{
if(this.InvokeRequired)
{
var d = new SafeCallDelegate(FillDataGrid);
Invoke(d, new object[] { dt });
}
else
{
//...
DataGridFiller(dt);
}
}
private void DataGridFiller(DataTable dt)
{
BindingSource dataSource = new BindingSource(dt, null);
//...
dgvData.DataSource = dataSource;
//...
frmLoading.Hide();
}
private void btnGetData_Click(object sender, EventArgs e)
{
DataTable dt = [...];
// Wenn Daten vorhanden sind, dann anzeigen
if (dt != null)
{
//...
frmLoading.Show();
thread1 = new Thread(() => FillDataGrid(dt));
thread1.Start();
}
}
}
}
The second approach is the correct one: use a BackgroundWorker to do any work that will freeze the UI if done in the main thread. About the exception you're getting, that's because the call you're making isn't thread-safe (Because the control was created on a different thread that the one whos calling its methods). Plase take a look at this link to MSDN to understand how to make this kind of call between threads, using backgroundWorker's event-driven model.
From the link:
There are two ways to safely call a Windows Forms control from a
thread that didn't create that control. You can use the
System.Windows.Forms.Control.Invoke method to call a delegate created
in the main thread, which in turn calls the control. Or, you can
implement a System.ComponentModel.BackgroundWorker, which uses an
event-driven model to separate work done in the background thread from
reporting on the results.
Take a look at the second example which demonstrates this technique using the backgroundWorker
EDIT
From your comments I get that the real problem here is size. The problem is that the thread that owns the DataGridView control, is the thread that is displaying it, so no matter how, if you load all the data at once it will freeze for the time it takes this thread to draw all that data on the screen. Fortunately you're not the first that had this problem, and microsoft got you covered this time. This is, I think, a great example of what the XY problem is, the real problem is that you want to load a huge dataset (X) and the answer on how to do that is here, but instead you asked how to display a loading icon while filling your datagrid whithout the UI freezing (Y), which was your attempted solution.
This was from a technical perspective but, from an UI/UX perspective I would like you to think about the actuall use of the form. Do you really need all that data loaded every time you visit this section? If the answer is no, maybe you could think about implementing some pagination (example here). Also 200 colums means horizontal scroll even for an ultrawide monitor. I can't really figure out the user case for you to need all that information on a list/table view at once. I think that maybe implemeting a Master-Detail kind of interface could be more useful.
EDIT 2.0
I think that you can try to create a whole new Form window in another thread, place it over your datagrid and paint the loading animation there. Meanwhile in the main window you can draw the grid without its painting making the loading animation freeze (the other thread is taking care of the drawing). You may want to hold a reference to the thread and kill it, or maybe better try to hold a reference to the From and close it more gracefully.
I've never done this but, I think I recall from some legacy application doing something like that, and it was ugly.
Use an asynchronous task that displays the pop-up loading window until the DataGridView is filled up.
Here's a link to a write-up Microsoft made for async programming: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/
So, I've been running into a problem with many of my WPF applications where after closing children windows of a window, that window (usually my main window) will go into background, behind anything else I have open. After some research, I found this bug report submitted to Microsoft: Bug Report and their usual response of "The WPF team has recently reviewed this issue and will not be addressing it..."
Has anyone been successful at tackling this on their own? It drives me mad and I can't figure out a solution.
EDIT:
I gave some thought to what James had recommended in his answer and after almost dismissing his suggestion due to the inconvenient nature of the window being on top of everything else, I came up with this:
ChildWindow.Closed += delegate
{
ChildWindow = null;
this.Topmost = true;
System.Threading.Thread.Sleep(1000);
this.Topmost = false;
};
So, when child's Closed() event is raised, I make sure that the parent window is the topmost. Then, I let the thread sleep for 1 second and set topmost to false to allow other windows to overlay this parent window.
Reason for the pause: If I don't use a pause and just this.Topmost = true followed by this.Topmost = false, then the effect never takes place and the bug still occurs because of the timing for the bug.
I'm not sure if it's the best way, but it works. Microsoft needs to invest more resources into WPF.
set the Main window to:
Topmost=true
This should help a little, but will not solve the issue entirely. Just keep in mind that if another application has the setting, they could end up on top of the application anyways. Let me know if this helps.
I would just have left a comment under the question, but I don't have enough reputation.
I encountered this very same issue, and after playing a little bit with the solution presented here, realized that a cleaner solution would be to call Focus() on the parent instead of making it topmost, set a timer, then remove topmost:
ChildWindow.Closed += delegate
{
ChildWindow = null;
parentWindow?.Focus();
};
This bug is indeed really annoying since it does not occur all the time and can sometimes be hard to reproduce. I know the OP asked about WPF but here is my workaround for WinForms so far (I prefered to avoid the Thread.Sleep(1000) so that the UI remains responsive):
ChildWindow.Closed += delegate { this.Activate(); };
I'm working on a Windows Phone App.
I have a very performance intensive method which takes several seconds until the operation is done.
When the method is called I want to show an animated loading symbol which is defined in the xaml of my view. When the operation is finished it should disappear. I set the loading symbol to visible in the first line of this method.In the last line I set the visibility to collapsed.
The problem is that at first the whole code behind will be executed. Unfortunately nothing is to be seen, because the the visibiliy is set to visible after the code behind operations are executed and in the same moment its set to collapsed.
Has anybody an idea how to solve this problem? Thanks so much in advance.
The problem you have is that you're calling your method on the main (UI) thread. This means that your method blocks the UI from refreshing, and also means that (as you noted) by the time the UI does refresh, you've already hidden the icon again.
What you need to do instead is call your method on a background thread (there are a number of ways to handle this). You will need to push the UI update to the UI thread (using Dispatcher.Invoke), but the rest of your method will run on a separate thread.
You'll also need to use a callback of some kind - maybe a custom event - so that your UI thread knows when the background thread is completed.
Without seeing the code its hard to say for sure but if you use the dispatcher to run you intensive code after the busy indicator is set this would allow the ui thread time to change before running the code.
An example
//This assumes you are binding in xaml to the isbusy and it implements INotifyPropertyChanged
IsBusy = true;
Dispatcher.BeginInvoke(()=>{ //...performance intense here
});
That being Said Dan Puzey is right. You should only run this logic on the UI thread if for some reason your need to. even then be wary of this as it makes for a poor ui experience.
One way you could accomplish this and still have your dispatcher fire off when you need would be to pass a copy of the dispatcher into the background.
ThreadPool.QueueUserWorkItem (d => {
//...performance intense here
Dispatcher dispatcher = d as Dispatcher;
if(dispatcher != null){
dispatcher.BeginInvoke()()=>{//...ui updates here }
}
}, Dispatcher.CurrentDispatcher);//make sure this is called from your UI thread or you may not end up with the correct dispatcher
Is there any way I can pause all UI Update commands in Winforms?
Or I have a slight feeling I'm trying to go about this the completely wrong way, so is there another way around my problem: I basically load a saved state of a control, which loads new controls all over it. However I do some of this in the UI thread, and some of the data loading from another thread, which then fills the UI.
So the effect I have when it is loading is that the user can see a few of the controls appearing in one place, then moving to another place on the form, changing values, etc.
I'd like to get a loading screen instead of this and load the controls in the background. It's quite a large application and its not THAT important so redesigning my code isn't really an option.
Can I simply stop all Update() commands on a control while a method is executing?
You can use the SuspendLayout and ResumeLayout methods to wrap the setup of UI in one operation (without the update of the rendering).
Basically (assuming SomeMethod is in the form class):
private void SomeMethod()
{
this.SuspendLayout();
// all UI setup
this.ResumeLayout();
}
it really depends on your form logic, in general you should not overload the Load or Show method with too much things so that the form can be shown and drawn quickly and always look responsive.
in some cases it could help to use the SuspendLayout and ResumeLayout methods, see here:
Control.SuspendLayout Method
I've got a Windows Forms (C#) project with multiple comboboxes/listboxes etc that are populated when the form loads.
The problem is that the loading of the comboboxes/listboxes is slow, and since the loading is done when the form is trying to display the entire form isn't shown until all the controls have been populated. This can in some circumstances be 20+ seconds.
Had there been a Form_finished_loaded type of event I could have put my code in there, but I can't find an event that is fired after the form is done drawing the basic controls.
I have one requirement though - the loading has to be done in the main thread (since I get the items from a non-threading friendly COM-application).
I have found one potential solution, but perhaps there is a better way?
I can create a System.Timer.Timer when creating the form, and have the first Tick be called about 1 second later, and then populate the lists from that tick. That gives the form enough time to be displayed before it starts filling the lists.
Does anyone have any other tips on how to delay the loading of the controls?
There is the Shown event that "occurs whenever the form is first displayed.". Also you may want to use the BeginUpdate and EndUpdate functions to make the populating of your combobox faster.
It has that certain smell of workaround, but this approach should fulfil your needs:
private bool _hasInitialized = false;
private void Form1_Shown(object sender, EventArgs e)
{
if (!_hasInitialized)
{
ThreadPool.QueueUserWorkItem(state =>
{
Thread.Sleep(200); // brief sleep to allow the main thread
// to paint the form nicely
this.Invoke((Action)delegate { LoadData(); });
});
}
}
private void LoadData()
{
// do the data loading
_hasInitialized = true;
}
What it does is that it reacts when the form is shown, checks if it has already been initialized before, and if not it spawns a thread that will wait for a brief moment before calling the LoadData method on the main thread. This will allow for the form to get painted properly. The samething could perhaps be achieve by simply calling this.Refresh() but I like the idea of letting the system decide how to do the work.
I would still try to push the data loading onto a worker thread, invoking back on the main thread for populating the UI (if it is at all possible with the COM component).
Can you get your data from a web service that calls the COM component?
That way, you can display empty controls on a Locked form at the start, make Asynchronous calls to get the data, and on return populate the respective combos, and once all of them are loaded, you can unlock the form for the user to use.
You could listen for the VisibleChanged event and the first time it's value is true you put your initialization code.
Isn't FormShown the event you're looking for?
When you say that you cannot use a background thread because of COM what do you mean? I am using many COM components within my apps and running them on background threads.
If you create a new thread as an STAThread you can probably load the ComboBox/ListBox on a Non-UI thread. IIRC the ThreadPool allocates worker threads as MTAThread so you'll need to actually create a thread manually instead of using ThreadPool.QueueUserWorkItem.