我在 C# 中做一個表單應用程式,它是一個從服務器接收帶有套接字的字串的客戶端,我有一個在接收函式內部運行無限回圈的執行緒。當我單擊一個按鈕時,我必須停止該執行緒,我嘗試使用一個布爾變數,但它不起作用,因為該函式卡在接收函式上,并且對布爾變數的控制在 when 仍然為真之前完成。我該怎么做才能停止這個執行緒?
這是執行緒運行的函式:
public void Prova()
{
while (true)
{
string str = frmRegister.c.Receive();
... doing things...
}
}
執行緒是這樣啟動的:
public Form1()
{
InitializeComponent();
t1 = new Thread(Prova);
t1.Start();
}
我必須在這里停止執行緒:
private void goBack_Click(object sender, EventArgs e)
{
new Form2().Show();
this.Hide();
}
以下是我對 CancellationToken 的嘗試:
private CancellationTokenSource tokenSource;
public void Prova(CancellationToken token)
{
while(!token.IsCancellationRequested){
while (true)
{
string str = frmRegister.c.Receive();
... doing things...
}
}
}
public Form1()
{
InitializeComponent();
tokenSource = new CancellationTokenSource();
var task = Task.Run(() => Prova(tokenSource.Token));
}
private void goBack_Click(object sender, EventArgs e)
{
tokenSource.Cancel();
new Form2().Show();
this.Hide();
}
uj5u.com熱心網友回復:
鑒于您的樣本,這應該可以作業:
private CancellationTokenSource tokenSource;
public void Prova(CancellationToken token = default)
{
while(!token.IsCancellationRequested) {
string str = frmRegister.c.Receive();
... doing things...
}
}
}
甚至:
public void Prova(CancellationToken token = default)
{
while (true)
{
token.ThrowIfCancellationRequested();
string str = frmRegister.c.Receive();
... doing things...
}
}
或者:
public void Prova(CancellationToken token = default)
{
while (true)
{
if(token.IsCancellationRequested)
return;
string str = frmRegister.c.Receive();
... doing things...
}
}
基本上擺脫了雙while回圈,它就可以作業了。
uj5u.com熱心網友回復:
你為什么用執行緒而不是任務?
在你的情況下
Thread th;
CancellationTokenSource cts = new CancellationTokenSource();
public void Prova(CancellationToken cancellationToken)
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
string str = frmRegister.c.Receive();
... doing things...
}
}
public Form1()
{
InitializeComponent();
th = new Thread(() => { Prova(cts.Token); });
th.Start();;
}
private void goBack_Click(object sender, EventArgs e)
{
cts.Cancel();
}
有任務
Task th;
CancellationTokenSource cts = new CancellationTokenSource();
public void Prova(CancellationToken cancellationToken)
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
...process
}
}
public Form1()
{
InitializeComponent();
th = Task.Run(() => { Prova(cts.Token); }, cts.Token);
th.Start(); ;
}
private void goBack_Click(object sender, EventArgs e)
{
cts.Cancel();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/422171.html
標籤:
