[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

In c#, wpf update the ui from a different thread doesn't work.

Posted on 2011-05-11
6
Medium Priority
?
840 Views
Last Modified: 2012-05-11
I am unable to update a textbox on my user interface from a different thread.

The code that starts the thread is:
private void fileButton_Click(object sender, RoutedEventArgs e)
{
     string filename = "filename.ext";
     Thread t = new Thread(() => SendFile(filename));
     t.Start();
}

Open in new window


Then in the SendFile function I try to update the ui:
private void SendFile(string filename)
{ 
    Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Send, new UpdateUiTextDelegate(WriteData), "filename is "+ filename);
}

Open in new window


and the code for the WriteData function is:
private void WriteData(string text)
{
     textBox.AppendText(text.ToString());
}

Open in new window


Am i trying to do the correct thing?  the program works, but the text "filename is  ..." does not display on the screen.  However the rest of the SendFile function (code is omitted in the function shown) works fine.
0
Comment
Question by:dazzler77
  • 3
  • 2
6 Comments
 
LVL 11

Assisted Solution

by:saragani
saragani earned 500 total points
ID: 35736501
Hi, as much as I remember and also according to mictosoft, CurrentDispatcher goes to the dispatcher which is associated to the thread you are calling it from:

http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx

So Dispatcher.CurrentDispatcher.BeginInvoke invokes the Text change on the new thread you have created instead of the Thread of the UI.


You need to run it in the Dispatcher of the UI, so do the following:
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Send, new UpdateUiTextDelegate(WriteData), "filename is "+ filename);

It works since the Application Thread is the same thread that created the UI.
0
 
LVL 11

Expert Comment

by:saragani
ID: 35736553
Btw, don't do code behind. You are using wpf, which means Binding.

Have a ViewModel (look for MVVM), and since the viewModel implements INotifyPropertChange, then the and the property change event is going through the dispatcher then it works like a charm.
... Plus you are building your code correctly with no business logic on your UI.
0
 
LVL 10

Accepted Solution

by:
oxyoo earned 500 total points
ID: 35736556
Try this..


private void SendFile(string filename)
{ 
   ThreadPool.QueueUserWorkItem(
		delegate {
			// DoWork!!
		
			this.Dispatcher.BeginInvoke( DispatcherPriority.Normal, new Action( () => textBox.AppendText(text.ToString()) ) );
		}
   );
}

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Closing Comment

by:dazzler77
ID: 35736883
thank you saragani and oxyoo.  Both solutions work well.
 
Also using ThreadPool.QueueUserWorkItem I was able to put all the code in there and not create an extra SendFile method.

I will also look into using INotifyPropertChange and binding more.
0
 
LVL 11

Expert Comment

by:saragani
ID: 35736920
Hi, you can do the same with my solution if you work with anonymous methods. For example:

Action action = delegate()
{
  // your code here.
};

Application.Current.Dispatcher.Invoke(action):



Something like that... Don't catch me for the exact syntax since I'm writing you from my iPhone, so I can't see if it compiles.
0
 

Author Comment

by:dazzler77
ID: 35737474
Thanks Saragani, your Action action = delegate() { ... };works too! - I just tried it.  After many many hours of no solution now I have lots of them ! thanks.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question