【发布时间】:2018-04-23 04:08:03
【问题描述】:
我在将值从 c# 代码绑定到 WPF UI 时遇到问题。 我已经了解了线程的基础知识,并且知道我必须使用 Dispatcher 来绑定自定义后台线程中的 ui 线程。
我有一个需求,我想通过每秒访问 nse-stockmarket api 并相应地执行一些逻辑来不断更新我的 WPF UI,以便我可以显示天气股价正在上涨或下跌。
下面是我试图实现这一目标的代码......
注意:我没有遇到任何异常,甚至“跨线程”也没有
//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;
});
}
当我使用 do-while 循环时,它会一直循环,直到我终止应用程序。在这个 do-while 循环中,我不断尝试通过使用“counter++;”更新 Text1 文本框来更新 WPF ui。
但它没有按预期工作。需要建议或解决方案。 :)
【问题讨论】:
-
这是一种非常古老的方法来运行并发任务,考虑使用任务,异步和等待,可能还有 WaitAll
-
除了@TheGeneral 的评论,您可能还想看看
DispatcherTimer。 -
你正在创建一个动作,但没有对它做任何事情。为什么不直接调用方法?但是其他人已经提到了使用 async/await 等更好的方法。
-
@MickyD 我已经解决了这个跨线程错误。即使下面的代码也没有抛出任何异常,它继续运行没有任何异常。唯一的问题是我的 ui 没有得到更新..
标签: c# wpf multithreading stock