1

My code which changes caption of navigation bar items:

OverviewOrgan_NavBarHelper cNavBarHelper = new OverviewOrgan_NavBarHelper(Organization);

foreach (NavBarItem item in GetNavigationBar.Items)
{                       
    string cCaption = cNavBarHelper.UpdateNavBarItemCaption(item);
    item.Caption = cCaption;
}

now it is on the main thread, but I have to move it to another thread. As I know that UI should not be changed from another threat, then it is made, so I thought about using BackgroundWorker. In fact, that I'm not in working with threads, can someone suggest the best solution for my task?

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
Edgar
  • 1,120
  • 4
  • 28
  • 53

3 Answers3

5

You can use Invoke to update the UI from another thread.

Take a look at this post: How to update the GUI from another thread in C#?

For Example:

MethodInvoker NavBarItemInvoker = (delegate
{
   OverviewOrgan_NavBarHelper cNavBarHelper = new OverviewOrgan_NavBarHelper(Organization);

   foreach (NavBarItem item in GetNavigationBar.Items)
   {                       
       string cCaption = cNavBarHelper.UpdateNavBarItemCaption(item);
       item.Caption = cCaption;
   }
});

if (InvokeRequired)
{
   Invoke(NavBarItemInvoker);
}
else
{
    NavBarItemInvoker();
}
Community
  • 1
  • 1
HaemEternal
  • 2,229
  • 6
  • 31
  • 50
  • NavBarItem not have invoke method – Edgar Jan 04 '13 at 10:27
  • You can let an other thread run code on the main thread. Look at the link he gave you. – Laurence Jan 04 '13 at 10:29
  • 1
    The NavBarItem does not have Invoke, but the NavBar itself - which is the owner of the item. Otherwise you can find the topmost form using Application.OpenForms and call Invoke on that form. Refer to [How to get main form](http://stackoverflow.com/questions/1000847/how-to-get-the-handle-of-the-topmost-form-in-a-winform-app) – Matthias Jan 04 '13 at 10:38
2

I think you should use a dispatcher for that

read more about it in this article: http://msdn.microsoft.com/en-us/magazine/cc163328.aspx

Moriya
  • 7,750
  • 3
  • 35
  • 53
2

have a look at the first answer in this thread. It explains how to use a BackgroundWorker.

But the problem will be, that the items of you navigationbar are created whithin the UI-Thread (assuming that you are using WPF) and those cannot be manipulated from another thread.

Why do you have to do it in another thread?

Community
  • 1
  • 1
medasocles
  • 61
  • 5