多线程c#WPF

将值从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。


但是它没有按预期工作。需要建议或解决方案。:)


catspeake
浏览 189回答 3
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;}
打开App,查看更多内容
随时随地看视频慕课网APP