C# 使用不同的线程更新GUI(WPF)

C# 使用不同的线程更新GUI(WPF),c#,multithreading,user-interface,sharing,C#,Multithreading,User Interface,Sharing,这里有个问题,我不知道怎么解决。我正在做一个小项目,其中涉及一个图形用户界面和串行数据。GUI由主线程运行,由于保存传入串行数据的数据变量需要不断更新,因此这些变量将在第二个线程中更新。问题是当我需要更新GUI上的一些文本框时,这些文本框需要使用来自辅助线程的数据进行更新,这就是我的问题所在。我不能直接从次线程更新它们,我也不知道如何从次线程传输数据,并制定出一个从主线程更新它们的系统。我把我的代码放在下面: 任何帮助都会很好 using System; using System.Collect

这里有个问题,我不知道怎么解决。我正在做一个小项目,其中涉及一个图形用户界面和串行数据。GUI由主线程运行,由于保存传入串行数据的数据变量需要不断更新,因此这些变量将在第二个线程中更新。问题是当我需要更新GUI上的一些文本框时,这些文本框需要使用来自辅助线程的数据进行更新,这就是我的问题所在。我不能直接从次线程更新它们,我也不知道如何从次线程传输数据,并制定出一个从主线程更新它们的系统。我把我的代码放在下面:

任何帮助都会很好

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.IO.Ports;
using System.Threading;

namespace GUIBike
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public static string inputdata;
        public static int MaximumSpeed, maximumRiderInput, RiderInput, Time, CurrentSpeed, DistanceTravelled, MaximumMotorOutput, MotorOutput, InputSpeed;
        public static string SaveDataString;
        public Thread Serial;
        public static SerialPort SerialData;
        public static string[] portlist = SerialPort.GetPortNames();
        public static string[] SaveData = new string[4];
        public static string directory = "C:\\";

        public MainWindow()
        {
            Serial = new Thread(ReadData);
            InitializeComponent();
            int Count = 0;
            for (Count = 0; Count < portlist.Length; Count++)
            {
                ComPortCombo.Items.Add(portlist[Count]);
            }
        }

        private void StartDataButton_Click(object sender, RoutedEventArgs e)
        {
            SerialData = new SerialPort(ComPortCombo.Text, 19200, Parity.None, 8, StopBits.One);
            SerialData.Open();
            SerialData.WriteLine("P");
            Serial.Start();
            StartDataButton.IsEnabled = false;
            EndDataButton.IsEnabled = true;
            ComPortCombo.IsEnabled = false;
            CurrentSpeed = 0;
            MaximumSpeed = 0;
            Time = 0;
            DistanceTravelled = 0;
            MotorOutput = 0;
            RiderInput = 0;
            SaveData[0] = "";
            SaveData[1] = "";
            SaveData[2] = "";
            SaveData[3] = "";
            SaveDataButton.IsEnabled = false;
            if (SerialData.IsOpen)
            {
                ComPortStatusLabel.Content = "OPEN";
                SerialData.NewLine = "/n";
                SerialData.WriteLine("0");
                SerialData.WriteLine("/n");
            }
        }

        private void EndDataButton_Click(object sender, RoutedEventArgs e)
        {
            SerialData.Close();
            SaveDataButton.IsEnabled = true;
            SerialData.WriteLine("1");
            SerialData.WriteLine("0");
            if (!SerialData.IsOpen)
            {
                ComPortStatusLabel.Content = "CLOSED";
            }
            int i = 0;
            for (i = 0; i < 4; i++)
            {
                if (i == 0)
                {
                    SaveDataString = "MaximumSpeed during the Ride was = " + Convert.ToString(MaximumSpeed) + "m/h";
                    SaveData[i] = SaveDataString;
                }
                if (i == 1)
                {
                    SaveDataString = "Total Distance Travelled = " + Convert.ToString(DistanceTravelled) + "m";
                    SaveData[i] = SaveDataString;
                }
                if (i == 2)
                {
                    SaveDataString = "Maximum Rider Input Power = " + Convert.ToString(maximumRiderInput) + "Watts";
                    SaveData[i] = SaveDataString;
                }
                if (i == 3)
                {
                    SaveDataString = "Maximum Motor Output Power = " + Convert.ToString(MaximumMotorOutput) + "Watts";
                    SaveData[i] = SaveDataString;
                }
            }
        }

        private void SaveDataButton_Click(object sender, RoutedEventArgs e)
        {
            //File.WriteAllBytes(directory + "image" + imageNO + ".txt", ); //saves the file to Disk    
            File.WriteAllLines(directory + "BikeData.txt", SaveData);
        }

        public void ReadData()
        {
            int counter = 0;

            while (SerialData.IsOpen)
            {
                if (counter == 0)
                {
                    //try
                    //{
                        InputSpeed = Convert.ToInt16(SerialData.ReadChar());
                        CurrentSpeed = InputSpeed;
                        if (CurrentSpeed > MaximumSpeed)
                        {
                            MaximumSpeed = CurrentSpeed;
                        }
                        SpeedTextBox.Text = "Current Wheel Speed = " + Convert.ToString(CurrentSpeed) + "Km/h";
                        DistanceTravelled = DistanceTravelled + (Convert.ToInt16(CurrentSpeed) * Time);
                        DistanceTravelledTextBox.Text = "Total Distance Travelled = " + Convert.ToString(DistanceTravelled) + "Km";
                    //}
                    //catch (Exception) { }
                }
                if (counter == 1)
                {
                    try
                    {
                        RiderInput = Convert.ToInt16(SerialData.ReadLine());
                        if (RiderInput > maximumRiderInput)
                        {
                            maximumRiderInput = RiderInput;
                        }
                        RiderInputTextBox.Text = "Current Rider Input Power =" + Convert.ToString(RiderInput) + "Watts";
                    }
                    catch (Exception) { }
                }
                if (counter == 2)
                {
                    try
                    {
                        MotorOutput = Convert.ToInt16(SerialData.ReadLine());
                        if (MotorOutput > MaximumMotorOutput)
                        {
                            MaximumMotorOutput = MotorOutput;
                        }

                        MotorOutputTextBox.Text = "Current Motor Output = " + Convert.ToString(MotorOutput) + "Watts";
                    }
                    catch (Exception) { }
                }
                counter++;
                if (counter == 3)
                {
                    counter = 0;
                }
            }
        }

        private void ComPortCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            StartDataButton.IsEnabled = true;
        }


        private void Window_Closed(object sender, RoutedEventArgs e)
        {
            if (SerialData.IsOpen)
            {
                SerialData.Close();
            }
        }
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;
使用System.Windows.Shapes;
使用System.IO;
使用System.IO.Ports;
使用系统线程;
名称空间导向自行车
{
/// 
///MainWindow.xaml的交互逻辑
/// 
公共部分类主窗口:窗口
{
公共静态字符串输入数据;
公共静态int最大速度、最大行车输入、行车输入、时间、当前速度、行驶距离、最大电机输出、电机输出、输入速度;
公共静态字符串SaveDataString;
公共线程序列;
公共静态串行端口串行数据;
公共静态字符串[]端口列表=SerialPort.GetPortNames();
公共静态字符串[]SaveData=新字符串[4];
公共静态字符串directory=“C:\\”;
公共主窗口()
{
串行=新线程(读取数据);
初始化组件();
整数计数=0;
for(Count=0;Count最大速度)
{
最大速度=当前速度;
}
SpeedTextBox.Text=“当前车轮速度=“+Convert.ToString(当前速度)+”Km/h”;
行驶距离=行驶距离+(转换为NT16(当前速度)*时间);
DistanceTraveledTextBox.Text=“行驶的总距离=“+Convert.ToString(DistanceTraveled)+”Km”;
//}
//捕获(异常){}
}
如果(计数器==1)
{
尝试
{
RiderInput=Convert.ToInt16(SerialData.ReadLine());
如果(RiderInput>maximumRiderInput)
{
public delegate void UpdateTextCallback(string message);

private void TestThread()
{
    for (int i = 0; i <= 1000000000; i++)
    {
        Thread.Sleep(1000);                
        richTextBox1.Dispatcher.Invoke(
            new UpdateTextCallback(this.UpdateText),
            new object[] { i.ToString() }
        );
    }
}
private void UpdateText(string message)
{
    richTextBox1.AppendText(message + "\n");
}

private void button1_Click(object sender, RoutedEventArgs e)
{
   Thread test = new Thread(new ThreadStart(TestThread));
   test.Start();
}
public void ReadData()
{
    int counter = 0;

    while (SerialData.IsOpen)
    {
        if (counter == 0)
        {
            //try
            //{
                InputSpeed = Convert.ToInt16(SerialData.ReadChar());
                CurrentSpeed = InputSpeed;
                if (CurrentSpeed > MaximumSpeed)
                {
                    MaximumSpeed = CurrentSpeed;
                }
    SpeedTextBox.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
        new Action(delegate() { SpeedTextBox.Text = "Current Wheel Speed = " + Convert.ToString(CurrentSpeed) + "Km/h"; });//update GUI from this thread


                DistanceTravelled = DistanceTravelled + (Convert.ToInt16(CurrentSpeed) * Time);

    DistanceTravelledTextBox.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
        new Action(delegate() {DistanceTravelledTextBox.Text = "Total Distance Travelled = " + Convert.ToString(DistanceTravelled) + "Km"; });//update GUI from this thread

            //}
            //catch (Exception) { }
        }
        if (counter == 1)
        {
            try
            {
                RiderInput = Convert.ToInt16(SerialData.ReadLine());
                if (RiderInput > maximumRiderInput)
                {
                    maximumRiderInput = RiderInput;
                }                       
    RiderInputTextBox.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, 
        new Action(delegate() { RiderInputTextBox.Text = "Current Rider Input Power =" + Convert.ToString(RiderInput) + "Watts"; });//update GUI from this thread
            }
            catch (Exception) { }
        }
        if (counter == 2)
        {
            try
            {
                MotorOutput = Convert.ToInt16(SerialData.ReadLine());
                if (MotorOutput > MaximumMotorOutput)
                {
                    MaximumMotorOutput = MotorOutput;
                }
    MotorOutputTextBox.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, 
        new Action(delegate() { MotorOutputTextBox.Text = "Current Motor Output = " + Convert.ToString(MotorOutput) + "Watts"; });//update GUI from this thread                        
            }
            catch (Exception) { }
        }
        counter++;
        if (counter == 3)
        {
            counter = 0;
        }
    }
}
new Thread(() => 
{
    while (...)
    {
        SomeTextBox.Dispatcher.BeginInvoke((Action)(() => SomeTextBox.Text = ...));
    }
}).Start();
     Public Void UpdateUI()
     {
         //Here update your label, button or any string related object.

         //Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));    
         Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
     }
myTextBlock.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                   new Action(delegate() 
                                      {
                                      myTextBlock.Text = Convert.ToString(myDataObject.getMeData());
                                      }));
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        new Thread(DoSomething).Start();
    }
    public void DoSomething()
    {
        for (int i = 0; i < 100000000; i++)
        {
               this.Dispatcher.Invoke(()=>{
               textbox.Text=i.ToString();
               });    
        } 
    }
<Window x:Class="WpfThreading.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfThreading"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="216.84">
<Grid Margin="0,0,2,0">
    <Button Content="Button" HorizontalAlignment="Left" Margin="10,10,0,0"
            VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    <TextBox HorizontalAlignment="Left" Margin="10,35,0,10" TextWrapping="Wrap" Name="mtextBox" Width="87"   VerticalScrollBarVisibility="Auto"/>
    <TextBox HorizontalAlignment="Left" Margin="111,35,0,10" TextWrapping="Wrap" x:Name="mtextBox2" Width="87"   VerticalScrollBarVisibility="Auto"/>
</Grid></Window>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        new Thread(DoSomething).Start();
        new Thread(DoSomething2).Start();
    }


    public void DoSomething()
    {
        for (int i = 0; i < 100; i++)
        {
            Dispatcher.BeginInvoke(new Action(() => {
                mtextBox.Text += $"{i.ToString()}{Environment.NewLine}";
            }), DispatcherPriority.SystemIdle);

            Thread.Sleep(100);
        }

    }

    public void DoSomething2()
    {
        for (int i = 100; i > 0; i--)
        {
            Dispatcher.BeginInvoke(new Action(() => {
                mtextBox2.Text += $"{i.ToString()}{Environment.NewLine}";
            }), DispatcherPriority.SystemIdle);

            Thread.Sleep(100);
        }

    }
}