Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)qq
published in(发表于) 2014/7/11 9:28:17
C#教程:线程的暂停与恢复

C#教程:线程的暂停与恢复

线程的暂停与恢复

线程通过调用Suspend方法来暂停线程。当线程针对自身调用Suspend 方法时,调用将会阻止,直到另一个线程继续该线程。当一个线程针对另一个线程调用.Suspend 方法时,调用是非组阻止调用,这会导致另一线程暂停。线程通过调用Resume方法来恢复被暂停的线程。无论调用了多少次Suspend方法,调用Resume方法均会使另一个线程脱离挂起状态,并导致该线程继续执行。

示例

线程的暂停与恢复

下面的代码实现了线程t的暂停与恢复。

private void Form1_Load(object sender, EventArgs e)

{

Thread t = new Thread(new ThreadStart(TestMethord));

t.Start();

t. Suspend();

MessageBox.Show("线程已暂停");

t. Resume ();

MessageBox.Show("线程已恢复");

}

public void TestMethord() //线程调用的自定义方法

{

}

完整程序代码如下:

★ ★★★★Form1.cs窗体代码文件完整程序代码★★★★★

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Threading;

namespace _8_01

{

public partial class Form1 : Form

{

Thread t;

public Form1()

{

InitializeComponent();

}

private void Form1_Load(object sender, EventArgs e)

{

t = new Thread(new ThreadStart(TestMethord));

t.Start();

t.Suspend();

MessageBox.Show("线程已暂停");

t.Resume();

MessageBox.Show("线程已恢复");

}

public void TestMethord() //线程调用的自定义方法

{

while (true)

{

}

}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)

{

t.Abort();

}

}

}

★ ★★★★Form1.designer.cs窗体设计文件完整程序代码★★★★★

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Threading;

namespace _8_01

{

public partial class Form1 : Form

{

Thread t;

public Form1()

{

InitializeComponent();

}

private void Form1_Load(object sender, EventArgs e)

{

t = new Thread(new ThreadStart(TestMethord));

t.Start();

t.Suspend();

MessageBox.Show("线程已暂停");

t.Resume();

MessageBox.Show("线程已恢复");

}

public void TestMethord() //线程调用的自定义方法

{

while (true)

{

}

}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)

{

t.Abort();

}

}

}

★ ★★★★Program.cs主程序文件完整程序代码★★★★★

using System;

using System.Collections.Generic;

using System.Windows.Forms;

namespace _8_01

{

static class Program

{

///



/// 应用程序的主入口点。

///


[STAThread]

static void Main()

{

Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

Application.Run(new Form1());

}

}

}




If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759