Show message in GUI when thread is running in C #

I have an application that, upon first launch and every 7 days, performs an update downloading some files from the Internet.

This update may take up to 5 minutes, depending on how many files are required to download.

What I'm going to do is run the update in a separate thread so that the rest of the GUI is used during update processing.

This seems like a pretty viable option for my application, but I would also like to show a message in the main GUI, perhaps in the status bar, which tells the user that the update is being processed and leaves when it is completed.

I was looking for ways to do this, but nothing looks like what I'm looking for. Does anyone know if this is possible and how to do it?

+3
source share
2 answers

All you have to do is wrap your passcode with help Dispatcher.Invokefrom the background thread. An instance Dispatcherfor use can be obtained using Dispatcheryour property UIElement.

Assuming that the method described below is defined in the definition of a class of user interface elements:

private void ProcessItems(IList<Item> items)
{
    Task.Factory.StartNew(() =>
    {
        for (int i = 0; i < items.Count; ++i)
        {
            // Code here runs on background thread.
            this.ProcessItem(items[i]);

            this.Dispatcher.Invoke(DispatcherPriority.Normal, () =>
            {
                // Code here runs on UI thread.
                this.UpdateStatus("Completed " + (i + 1) + " of " + items.Count);
            });
        }
    },
        TaskCreationOptions.LongRunning);
}
+6
source

With this little guy:

internal static class ControlExtensions
{
    internal static void Invoke(this Control control, Action action)
    {
        control.Invoke(action);
    }
 }

you can call your code (in the win form world, wpf has its own solution):

... form.Invoke(()=>form.SomeControl.SomeProperty=someValue);
0
source

All Articles