I am facing an issue while binding value from c# code to WPF UI. I have gone through the basic of threading and come to know that I have to use the Dispatcher to bind the ui-thread from my custom background thread.
I have a requirement of like, I want to update my WPF UI continuously by hitting the nse-stockmarket api every second and the do some logic accordingly so that I can show weather share price is increasing or decreasing.
Below is the code how I am trying to achieve this...
Note: I am not getting any kind of exception not even "CROSS-Thread"
//globally declared var stockName = "";
//wpf button click
private void Button_Click(object sender, RoutedEventArgs e)
{
stockName = "LUPIN";
new Thread(() =>
{
RunStockParallel(share.Key);
Action action = new Action(SetTextBoxValues);
}).Start();
}
public void RunStockParallel(string stockName){
var count = 0 ;
do
{
HttpWebRequest stocks = null;
try
{
//your logic will be here..
}
catch (Exception e)
{
//throw e;
}
//It will call the delegate method so that UI can update.
Action action = new Action(SetTextBoxValues);
stockName = count++;
} while (true);
}
private void SetTextBoxValues()
{
this.Dispatcher.Invoke(() =>
{
this.text1.Text = stockName;
});
}
As I am using do-while loop, it will keep looping until I terminate the application. In this do-while loop I am continuously trying to update the WPF ui by update the Text1 textbox with this "counter++;".
But its not working as expected. Need suggestion or solution. :)