Reputation: 646
private void button1_Click(object sender, RoutedEventArgs e)
{
new Thread(delegate() { doTest(); }).Start();
}
When doTest() included with in the mainwindow , as below , my textbox is updating from the thread , i can see text box value changing ( so updating value from thread is working .
public void doTest()
{
int count = 20;
while (count < 30)
{
Dispatcher.Invoke(new Action(() => txtBoxLog.Text = count.ToString()), null);
count++;
Thread.Sleep(500);
}
}
But , if i remove the above code and make separate class , placing outside the main window class , updating my text box from the thread is failing and i m not getting any error but the simply not changing its value , i updating from thread using dispatcher not updating .
to access mainwindow from doTest() class i created internal static main winodwo calss tw
internal static MainWindow tw;
and now my doTest() method have following code in clsTest.cs file
internal class clsTest
{
public clsTest() { }
public void doTest()
{
int count = 20;
while (count < 30)
{
MainWindow.tw.Dispatcher.Invoke(
new Action(() => MainWindow.tw.txtLog.Text = count.ToString()), DispatcherPriority.Background, null);
count++;
Thread.Sleep(500);
}
}
}
please , assist me to identify where i am getting wrong here ..
Upvotes: 0
Views: 2471
Reputation: 1472
There is nothing obviously wrong with what you have posted. They look fine to me, and I double checked by running your snippets in a sample app. I would guess that it is something to do with how you are initialising the static "tw" MainWindow instance which you have not shown.
edit: Okay you should not be explicitly creating a new MainWindow instance like you are doing since WPF automatically creates one for you. Instead you should be setting that static instance to point at the default instance, e.g. in the constructor of your MainWindow class:
internal static MainWindow tw;
public MainWindow()
{
InitializeComponent();
tw = this;
}
Upvotes: 1
Reputation: 381
Don't you need to initialize the tw
as tw = this
instead of tw = new MainWindow()
?
Upvotes: 0