除停止按鈕之外的所有內容均可正常工作。 (按鈕3和按鈕4 OnClick):對多線程應用程序中的按鈕單擊沒有任何影響
我做了一個有四個按鈕的應用程序。
這是一個多線程應用程序。
按鈕1和2將開始產卵線程。
按鈕3和4將分別停止該過程。
但它似乎沒有工作。
這裏是我的代碼:
public partial class Form1: Form
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token;
public Form1()
{
InitializeComponent();
token = cancellationTokenSource.Token;
}
private void button1_Click(object sender, EventArgs e)
{
Task t = Task.Run(() =>
{
while (true)
{
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(1000);
Action act =() => textBox1.Text = Convert.ToString(i);
textBox1.Invoke(act);
}
if (token.IsCancellationRequested)
{
token.ThrowIfCancellationRequested();
}
}
}, token);
}
private void button2_Click(object sender, EventArgs e)
{
//token.Cancel();
}
private void button3_Click(object sender, EventArgs e)
{
Task t1 = Task.Run(() =>
{
while (true)
{
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(1000);
Action act =() => textBox2.Text = Convert.ToString(i);
textBox2.Invoke(act);
}
if (token.IsCancellationRequested)
{
token.ThrowIfCancellationRequested();
}
}
}, token);
}
private void button4_Click(object sender, EventArgs e)
{
//token.Cancel();
}
}
更新
下面是更新後的代碼:
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MultiThreading_Start_Stop_Counter
{
public partial class Form1 : Form
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token;
CancellationTokenSource cancellationTokenSource1 = new CancellationTokenSource();
CancellationToken token1;
public Form1()
{
InitializeComponent();
token = cancellationTokenSource.Token;
token1 = cancellationTokenSource1.Token;
}
private void button1_Click(object sender, EventArgs e)
{
Task t = Task.Run(() =>
{
for (int i = 0; i < 10; i++)
{
if (token.IsCancellationRequested)
{
token.ThrowIfCancellationRequested();
}
// your code
System.Threading.Thread.Sleep(1000);
Action act =() => textBox1.Text = Convert.ToString(i);
textBox1.Invoke(act);
}
});
}
private void button2_Click(object sender, EventArgs e)
{
cancellationTokenSource.Cancel();
}
private void button3_Click(object sender, EventArgs e)
{
Task t1 = Task.Run(() =>
{
for (int i = 0; i < 10; i++)
{
if (token1.IsCancellationRequested)
{
token1.ThrowIfCancellationRequested();
}
// your code
System.Threading.Thread.Sleep(1000);
Action act =() => textBox2.Text = Convert.ToString(i);
textBox2.Invoke(act);
}
});
}
private void button4_Click(object sender, EventArgs e)
{
cancellationTokenSource1.Cancel();
}
}
}
現在的任務是消除,但與此異常:
的ty的例外pe'System.OperationCanceledException'發生在mscorlib.dll中,但未在用戶代碼中處理 附加信息:操作已取消。
解決:
使用while循環。謝謝!
你得到一個錯誤,指出錯誤CancellationTokenSource和的CancellationToken?而不是while(true)做類似while(!token.IsCancellationRequested) – Trey