如何使用resume()回调挂起的线程 [英] How to call back the thread which is suspended using resume()
本文介绍了如何使用resume()回调挂起的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用resume()执行剩余的迭代?
How to use resume()to execute remaining iterations?
namespace CAthreads
{
class clsthread2
{
public void thread1()
{
for (int i = 0; i < 10; i++)
{
Thread t1 = Thread.CurrentThread;
Console.WriteLine(t1.Name + "=" + i);
if (i == 5)
{
Console.WriteLine(t1.Name + " is going to suspend");
t1.Suspend();
}
}
}
class Class1
{
static void Main()
{
clsthread2 obj1 = new clsthread2();
ThreadStart tstart1 = new ThreadStart(obj1.thread1);
ThreadStart tstart2 = new ThreadStart(obj1.thread1);
Thread thr1 = new Thread(tstart1);
Thread thr2 = new Thread(tstart1);
thr1.Name = "NTR";
thr2.Name = "ANR";
thr1.Start();
thr2.Start();
Console.Read();
}
}
}
推荐答案
对于初学者来说,暂停和恢复是过时的,并且根据到MSDN:将在未来版本中删除。 ( http://msdn.microsoft.com/en-us/library/ tttdef8x(v = vs.110).aspx [ ^ ])
这意味着您不应该使用它们,因为它们明天可能无法使用!
你应该使用 WaitHandles [< a href =http://msdn.microsoft.com/en-us/library/ms228964(v=vs.110).aspx\"target =_ blanktitle =New Window> ^ ] - 它们更灵活,不会过时...
尝试 WaitOne [ ^ ] - 它包含一个示例。
For starters, Suspend and Resume are obsolete, and according to MSDN: "will be removed in a future release." (http://msdn.microsoft.com/en-us/library/tttdef8x(v=vs.110).aspx[^])
This means you should not be using them, as they may not work tomorrow!
You should be using WaitHandles[^] instead - they are much more flexible and not obsolete...
Try WaitOne[^] - it includes an example.
如果你想将线程恢复到其他类,那么这将是hel你...
我已更新你的代码....
If you wanted to Resume thread into other class then this will help you...
I have updated your code....
namespace CAthreads
{
class clsthread2
{
Thread t1;
public void thread1()
{
for (int i = 0; i < 10; i++)
{
t1 = Thread.CurrentThread;
Console.WriteLine(t1.Name + "=" + i);
if (i == 5)
{
Console.WriteLine(t1.Name + " is going to suspend");
t1.Suspend();
}
}
}
// Created new method to resume thread...
public void ResumeThread()
{
if (t1.ThreadState == ThreadState.Suspended)
{
t1.Resume();
}
}
}
class Class1
{
static void Main()
{
clsthread2 obj1 = new clsthread2();
obj1.ResumeThread(); //Method of Class clsthread2
ThreadStart tstart1 = new ThreadStart(obj1.thread1);
ThreadStart tstart2 = new ThreadStart(obj1.thread1);
Thread thr1 = new Thread(tstart1);
Thread thr2 = new Thread(tstart1);
thr1.Name = "NTR";
thr2.Name = "ANR";
thr1.Start();
thr2.Start();
Console.Read();
}
}
}
这篇关于如何使用resume()回调挂起的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文