通过文本框在文本文件中显示单词

本文关键字:文本 显示 文件 单词 | 更新日期: 2023-09-27 17:56:03

我的代码只是读取文件,将其拆分为单词,并以0.1秒的频率在文本框中输入每个单词。

我单击以"button1"以获取文件并拆分。

单击Start_Button后,程序卡住了。我在代码中看不到任何问题。请问谁能看到吗?

我的代码在这里;

 public partial class Form1 : Form
    {
        string text1, WordToShow;
        string[] WordsOfFile;
        bool LoopCheck;
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {           
            OpenFileDialog BrowseFile1 = new OpenFileDialog();
            BrowseFile1.Title = "Select a text file";
            BrowseFile1.Filter = "Text File |*.txt";
            BrowseFile1.FilterIndex = 1;
            string ContainingFolder = AppDomain.CurrentDomain.BaseDirectory;
            BrowseFile1.InitialDirectory = @ContainingFolder;
            //BrowseFile1.InitialDirectory = @"C:'";
            BrowseFile1.RestoreDirectory = true;
            if (BrowseFile1.ShowDialog() == DialogResult.OK)
            {
                text1 = System.IO.File.ReadAllText(BrowseFile1.FileName);
                WordsOfFile = text1.Split(' ');
                textBox1.Text = text1;
            }
        }
        private void Start_Button_Click(object sender, EventArgs e)
        {
            timer1.Interval = 100;
            timer1.Enabled = true;
            timer1.Start();
            LoopCheck = true;
            try
            {
                while (LoopCheck)
                {
                    foreach (string word in WordsOfFile)
                    {
                        WordToShow = word;
                        Thread.Sleep(1000);
                    }
                }
            }
            catch
            {
                Form2 ErrorPopup = new Form2();
                if (ErrorPopup.ShowDialog() == DialogResult.OK)
                {
                    ErrorPopup.Dispose();
                }
            }
        }
        private void Stop_Button_Click(object sender, EventArgs e)
        {
            LoopCheck = false;
            timer1.Stop();
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            textBox1.Text = WordToShow;
        }
    }
}

通过文本框在文本文件中显示单词

与其

Thread.Sleep(1000); async/await功能与Task.Delay一起使用,以保持UI负责:

private async void Start_Button_Click(object sender, EventArgs e)
    {
        timer1.Interval = 100;
        timer1.Enabled = true;
        timer1.Start();
        LoopCheck = true;
        try
        {
            while (LoopCheck)
            {
                foreach (string word in WordsOfFile)
                {
                    WordToShow = word;
                    await Task.Delay(1000);
                }
            }
        }
        catch
        {
            Form2 ErrorPopup = new Form2();
            if (ErrorPopup.ShowDialog() == DialogResult.OK)
            {
                ErrorPopup.Dispose();
            }
        }
    }