我有一个在 Thread 中调用的方法。这是方法..
private System.Threading.Thread _thread;
private ManualResetEvent _shutdownEvent = new ManualResetEvent(false);
private void DoWork()
{
while (!_shutdownEvent.WaitOne(0))
{
//Business logic
}
}
现在我开始线程..
_thread = new Thread(DoWork);
_thread.Start();
现在根据我的要求我想关闭并重新启动线程..为了关闭和重新启动我正在尝试这段代码..
_shutdownEvent.Set(); // trigger the thread to stop
_thread.Join();
但我认为这不是关闭线程并重新启动它的正确方法..
请帮助我关闭并重新启动线程。 提前致谢..
最佳答案
我建议您查看 Task Parallel Library
,它可以对其执行进行细粒度控制,并且 supports a cancellation mechanism通过 CancellationToken
结构:
这是一个例子:
var tokenSource = new CancellationTokenSource();
CancellationToken ct = tokenSource.Token;
var task = Task.Factory.StartNew(() =>
{
// Were we already canceled?
ct.ThrowIfCancellationRequested();
bool moreToDo = true;
while (moreToDo)
{
// Poll on this property if you have to do
// other cleanup before throwing.
if (ct.IsCancellationRequested)
{
// Clean up here, then...
ct.ThrowIfCancellationRequested();
}
}
}, tokenSource.Token); // Pass same token to StartNew.
tokenSource.Cancel();
关于“重启线程”,您不能重启给定的Task
。您可以做的是看到它已被取消(任务包含一个 Status
属性,一旦您取消,该属性将变为 Canceled
),如果是,则执行一个新任务。
关于c# - 如何在c#中正确关闭线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26116010/