如何使方法在“后台"环境中运行(线程?) [英] How to make a method run in the "background" (threading?)
本文介绍了如何使方法在“后台"环境中运行(线程?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前有一些代码可以在文本文件中循环查找特定的短语.但是,运行此方法时,整个应用程序将锁定.我想是因为它在循环,这就是我想要的.
I currently have some code that cycles through a text file looking for a specific phrase. However, when this method runs, the whole application locks up. I assume because it's looping, which is what I want.
我希望这种情况在后台发生,因此仍然可以完成常规方法和用户与应用程序的交互.
I would like this to happen in the background, so normal methods and user interaction with the application can still be done.
如何做到/改善呢?
private void CheckLog()
{
while (true)
{
// lets get a break
Thread.Sleep(5000);
if (!File.Exists("Command.bat"))
{
continue;
}
using (StreamReader sr = File.OpenText("Command.bat"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/"))
{
// output it
MessageBox.Show(s);
}
}
}
}
}
推荐答案
使用
class Foo {
private Thread thread;
private void CheckLog() {...}
private void StartObserving() {
thread = new Thread(this.CheckLog);
thread.Start();
}
}
或调色板中的backgroundworker组件.
or the backgroundworker component from the palette.
这篇关于如何使方法在“后台"环境中运行(线程?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文