C# 通过文本框显示文本文件中的单词?
我的代码只是读取文件,将其拆分为单词,然后以0.1秒的频率在文本框中对每个单词进行命名 我点击C# 通过文本框显示文本文件中的单词?,c#,file-io,C#,File Io,我的代码只是读取文件,将其拆分为单词,然后以0.1秒的频率在文本框中对每个单词进行命名 我点击“button1”获取文件并拆分 单击Start\u按钮后,程序卡住。我看不出代码中有任何问题。有人能看一下吗 我的代码在这里 public partial class Form1 : Form { string text1, WordToShow; string[] WordsOfFile; bool LoopCheck; pu
“button1”
获取文件并拆分
单击Start\u按钮后,程序卡住。我看不出代码中有任何问题。有人能看一下吗
我的代码在这里
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)代码>将异步/等待
功能与任务一起使用。延迟
以使您的用户界面
负责:
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();
}
}
}
这就解决了问题。非常感谢。但是我不明白为什么会有一个Thread.Sleep()方法,而我们有这样一个更可靠的方法?