《MAC如何設定環境配置永久生效》
阿新 • • 發佈:2021-02-13
C#兩種程序暫停和繼續的方法
方法一
可以使用Thread.Suspend和Thread.Resume這兩個方法。
namespace ThreadSuspended
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void text()
{
for (int i = 0; i < 100000; i++)
{
Invoke(new Action(() => txt_Count.Text = i.ToString()));
//txt_Count.Text = i.ToString();
}
}
private Thread th;
private void Btn_Start_Click(object sender, EventArgs e)
{
th = new Thread(new ThreadStart(text));
th.Start();
th.IsBackground = true;//使th為後臺執行緒在關閉Form1時後臺執行緒一起關閉,如果前臺執行緒則不被關閉引發錯誤
}
private void Btn_Pause_Click(object sender, EventArgs e)//暫停按鈕
{
if (th.ThreadState != ThreadState.Suspended)//如果執行緒沒有掛起
{
//掛起執行緒
th.Suspend();
}
}
private void Btn_Continue_Click(object sender, EventArgs e)//繼續按鈕
{
if (th != null && th.ThreadState != ThreadState.Running )
{
//繼續執行
th.Resume();
}
}
}
}
如圖(一)所示
這裡面要注意的是呼叫文字框txt_Count必須要使用委託的方法Invoke(new Action(() => txt_Count.Text = i.ToString()));
開始控制元件名稱: btn_Start 開始事件:Btn_Start_Click(object sender, EventArgs e)
暫停控制元件名稱:btn_Pause 暫停事件:Btn_Pause_Click(object sender, EventArgs e)
繼續控制元件名稱:btn_Continue 繼續事件:Btn_Continue_Click(object sender, EventArgs e)
方法二
使用ManualResetEvent, ManualResetEvent 是一個類它會通知一個或多個正在等待的執行緒已發生事件。 此類不能被繼承。
namespace ThreadSuspended
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ManualResetEvent mre = new ManualResetEvent(true);
private void text()
{
for (int i = 0; i < 100000; i++)
{
mre.WaitOne();
Invoke(new Action(() => txt_Count.Text = i.ToString()));
//txt_Count.Text = i.ToString();
}
}
private Thread th;
private void Btn_Start_Click(object sender, EventArgs e)
{
th = new Thread(new ThreadStart(text));
th.Start();
th.IsBackground = true;//使th為後臺執行緒在關閉Form1時後臺執行緒一起關閉,如果前臺執行緒則不被關閉引發錯誤
}
private void Btn_Pause_Click(object sender, EventArgs e)//暫停按鈕
{
mre.Reset();
}
private void Btn_Continue_Click(object sender, EventArgs e)//繼續按鈕
{
mre.Set();
}
}
}
效果如圖一所示結果一樣,與方法一不一樣的是在for迴圈中加入mre.WaitOne();這段程式碼的作用就是
// 摘要:
// 阻止當前執行緒,直到當前 System.Threading.WaitHandle 收到訊號。
//
// 返回結果:
// 如果當前例項收到訊號,則為 true。 如果當前例項永遠收不到訊號,則 System.Threading.WaitHandle.WaitOne(System.Int32,System.Boolean)
// 永不返回。
//
// 異常:
// T:System.ObjectDisposedException:
// 當前例項已被釋放。
//
// T:System.Threading.AbandonedMutexException:
// 執行緒退出時未釋放互斥體,等待過程已終止。 在 Windows 98 或 Windows Millennium Edition 中不引發此異常。
//
// T:System.InvalidOperationException:
// 當前例項是另一個應用程式域中的 System.Threading.WaitHandle 的透明代理。