【发布时间】:2010-12-22 12:16:55
【问题描述】:
在我的应用程序中,我正在通过另一个线程(其他那个 GUI 线程)执行我的文件读取。有两个按钮分别暂停和恢复线程。
private void BtnStopAutoUpd_Click(object sender, EventArgs e)
{
autoReadThread.Suspend();
}
private void BtnStartAutoUpd_Click(object sender, EventArgs e)
{
autoReadThread.Resume();
}
但我正面临这个警告,
Thread.Suspend 已被弃用。请使用 System.Threading 中的其他类,例如 Monitor、Mutex、Event 和 Semaphore,以同步线程或保护资源。 http://go.microsoft.com/fwlink/?linkid=14202
我如何只运行单线程(而不是 GUI 线程),所以我如何在此处应用同步或监控。
更新代码:
class ThreadClass
{
// This delegate enables asynchronous calls for setting the text property on a richTextBox control.
delegate void UpdateTextCallback(object text);
// create thread that perform actual task
public Thread autoReadThread = null;
public ManualResetEvent _event = new ManualResetEvent(true);
// a new reference to rich text box
System.Windows.Forms.RichTextBox Textbox = null;
private volatile bool _run;
public bool Run
{
get { return _run; }
set { _run = value; }
}
public ThreadClass(string name, System.Windows.Forms.RichTextBox r1)
{
Textbox = r1;
Run = true;
this.autoReadThread = new Thread(new ParameterizedThreadStart(UpdateText));
this.autoReadThread.Start(name);
}
private void UpdateText(object fileName)
{
//while (true)
//{
// _event.WaitOne();
while (Run)
{
if (Textbox.InvokeRequired)
{
UpdateTextCallback back = new UpdateTextCallback(UpdateText);
Textbox.BeginInvoke(back, new object[] { fileName });
Thread.Sleep(1000);
}
else
{
string fileToUpdate = (string)fileName;
using (StreamReader readerStream = new StreamReader(fileToUpdate))
{
Textbox.Text = readerStream.ReadToEnd();
}
break;
//}
}
}
}
}
}
run 是 bool 值,一个线程控制它(最初它是真的)
为了启动线程,我正在其他类中创建这个类实例(这个启动线程也是)
【问题讨论】:
-
你更新不显示:a)你的线程是如何启动的,b)完整的线程方法。
-
InvokeRequired 始终为真。你的线程没有做任何有用的事情,一切都在 UI 线程上运行。
标签: c# .net multithreading monitoring deadlock