为了账号安全,请及时绑定邮箱和手机立即绑定

多线程c#WPF

多线程c#WPF

C#
catspeake 2021-05-06 09:09:47
将值从C#代码绑定到WPF UI时遇到问题。我已经了解了线程的基础知识,并且知道我必须使用Dispatcher来绑定自定义后台线程中的ui线程。我有一个类似的要求,我想通过每秒点击nse-stockmarket api来不断更新我的WPF UI,并相应地执行一些逻辑,以便我可以显示天气股价正在上升或下降。以下是我如何尝试实现此目标的代码...注意:我什至没有“ 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;            });        }当我使用do-while循环时,它将一直循环直到我终止应用程序。在此do-while循环中,我不断尝试通过使用此“ counter ++;”更新Text1文本框来更新WPF ui。但是它没有按预期工作。需要建议或解决方案。:)
查看完整描述

3 回答

?
米脂

TA贡献1836条经验 获得超3个赞

我得到了一个答案。.我在try catch块内的RunStockParallel方法中的代码下面添加了代码。


HttpWebRequest stocks = null;

try

{

   //your logic will be here.. 


       Dispatcher.BeginInvoke(new Action(() =>

       {

           txtName.Text = stockName;



       }), DispatcherPriority.Background);


}

catch (Exception e)

{

   //throw e;

}


查看完整回答
反对 回复 2021-05-08
  • 3 回答
  • 0 关注
  • 169 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信