我是 .net 的新手,我正在尝试在一个窗口上应用两个线程
该应用程序包含两个按钮(开始和停止)和一个只读文本框,当用户单击启动时,程序将从 com 端口读取并将其附加到文本框,当单击停止时它将停止。问题是每当我点击启动程序时卡住
只是为了让它更短,我使用了“Hello World!”。
C#代码:
using System;
using System.Windows;
using System.Threading;
namespace ThreadingTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private bool _continue = false;
public MainWindow()
{
InitializeComponent();
}
private void startWrite(object sender, RoutedEventArgs e)
{
startButton.IsEnabled = false;
stopButton.IsEnabled = true;
_continue = true;
Dispatcher.Invoke((Action)(() =>
{
Hello();
}));
}
private void stopWrite(object sender, RoutedEventArgs e)
{
startButton.IsEnabled = true;
stopButton.IsEnabled = false;
_continue = false;
}
public void Hello()
{
while (_continue)
{
HelloText.AppendText("Hello World!\n");
//_continue = false;
}
}
}
}
xml代码:
<Window x:Class="ThreadingTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="296" Width="301"
Background="WhiteSmoke">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="245*" />
<RowDefinition Height="12*" />
</Grid.RowDefinitions>
<TextBox Name="HelloText"
IsReadOnly="True"
HorizontalAlignment="Left"
Margin="12,12,0,0"
VerticalAlignment="Top"
Height="233"
Width="174" />
<Button Name="startButton"
IsEnabled="True"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Height="25"
Width="50"
Margin="208,12,0,0"
Content="Start"
Click="startWrite" />
<Button Name="stopButton"
IsEnabled="False"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Height="25"
Width="50"
Margin="208,45,0,0"
Content="Stop"
Click="stopWrite" />
</Grid>
</Window>
对不起我的英语