I'm new to .net and i'm trying to apply two threads on one window
The application contains two buttons (start and stop) and one read only textbox when the user click on start the program will read from the com port and append it to the textbox and when click on stop it will stop. The problem is whenever i click on start the program stuck
only to make it shorter here i used "Hello World!".
C# code:
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; } } } } xaml code:
<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> and sorry for my English