gpt4 book ai didi

C# Threading.Suspend 已过时,线程已被弃用?

转载 作者:可可西里 更新时间:2023-11-01 08:40:01 27 4
gpt4 key购买 nike

在我的应用程序中,我正在通过另一个线程(GUI 线程除外)执行文件读取。有两个按钮分别用于暂停和恢复线程。

private void BtnStopAutoUpd_Click(object sender, EventArgs e) 
{
autoReadThread.Suspend();
}

private void BtnStartAutoUpd_Click(object sender, EventArgs e)
{
autoReadThread.Resume();
}

但我正面临这个警告,

Thread.Suspend has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. http://go.microsoft.com/fwlink/?linkid=14202

无论如何,我只运行一个线程(而不是一个 GUI 线程),所以我如何在这里应用同步或监控。

更新代码:

class ThreadClass 
{

// This delegate enables asynchronous calls for setting the text property on a rich text box 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;
}
}
}

}

运行是bool值,一个线程控制它(最初是真的)

为了启动一个线程,我在另一个类中创建了这个类实例(这个启动线程也是)

最佳答案

 //true makes the thread start as "running", false makes it wait on _event.Set()
ManualResetEvent _event = new ManualResetEvent(true);
Thread _thread = new Thread(ThreadFunc);

public void ThreadFunc(object state)
{
while (true)
{
_event.Wait();

//do operations here
}
}


_thread.Start();

// to suspend thread.
_event.Reset();

//to resume thread
_event.Set();

注意,所有操作都在线程“挂起”之前完成

你想要什么

private void ThreadFunc(object fileName)
{
string fileToUpdate = (string)fileName;
while (Run)
{
_event.WaitOne();

string data;
using (StreamReader readerStream = new StreamReader(fileToUpdate))
{
data = readerStream.ReadToEnd();
}

if (Textbox.InvokeRequired)
{
UpdateTextCallback back = new UpdateTextCallback(UpdateText);
Textbox.BeginInvoke(back, new object[] { data });
}

Thread.Sleep(1000);
}
}


private void UpdateText(string data)
{
Textbox.Text = data;
}

关于C# Threading.Suspend 已过时,线程已被弃用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4509067/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com