當我的計時器完成時,我需要停止一個執行緒。
但這一切都來自另一個功能。
我的定時器在按下鍵后啟動:L。一個訊息框出現“定時器啟動”,我的執行緒也開始了。10 秒后,計時器停止并顯示訊息,但我的執行緒仍在運行。我能做些什么?:/
void StartFunction()
{
Thread AB = new Thread(SEARCHING) { IsBackground = true };
AB.Start();
}
void StopFunction()
{
Thread AB = new Thread(SEARCHING);
AB.Abort();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.L)
{
StartFunction();
timer1.Start();
MessageBox.Show("Timer 1 started!");
}
}
int time = 0;
private void timer1_Tick(object sender, EventArgs e)
{
time ;
if (time == 10 && timer1.Enabled)
{
StopFunction();
MessageBox.Show("Timer 1 stoped!");
timer1.Stop();
time = 0;
}
}
uj5u.com熱心網友回復:
使用現代方法,您將撰寫類似
private async void Form1_KeyDown(object sender, KeyEventArgs e)
{
var cts = new CancellationTokenSource(10000);
var task = Task.Run(() => Search(cts.Token));
try
{
var result = await task;
// handle result
}
catch (OperationCanceledException)
{
// handle cancelled
}
catch (Exception)
{
// handle other exceptions
}
}
public int Search(CancellationToken cancel)
{
while (true)
{
cancel.ThrowIfCancellationRequested();
// Do searching
if (found)
return result;
}
}
這將使用執行緒池執行緒而不是專用執行緒,并避免手動管理計時器的需要。它還可以輕松處理操作的結果(如果有的話)。
uj5u.com熱心網友回復:
Idle_Mind 關于如何實作這一點是正確的。下面是一個使用 .NET 6 的作業示例。
一個重要的細節是使用Thread.Join(). 這將告訴你的呼叫者阻塞,直到回圈退出并且方法回傳。
這里我使用命令控制臺來關閉_running標志的切換。你可以用計時器或其他任何東西來做同樣的事情。請記住,您可能還應該IDisposable在包含執行緒的類中實作并設定_running為 false 并在那里進行連接。這樣,您可以使用using.
namespace Lala
{
class AB : IDisposable
{
private bool _running = false;
private readonly Thread _thread;
public AB() => _thread = new Thread(Method);
private void Method()
{
while (_running)
{
Console.WriteLine("doing stuff");
Thread.Sleep(1000);
}
}
public void StartMethod()
{
_running = true;
_thread.Start();
}
public void StopMethod()
{
_running = false;
_thread.Join();
}
public void Dispose() => StopMethod();
}
public class Program
{
public static void Main()
{
Console.WriteLine("Launching a Thread. Press any key to stop it");
using AB ab = new();
// AB ab = new(); // if using is not appropriate
ab.StartMethod();
while (!Console.KeyAvailable)
Thread.Sleep(10);
// ab.StopMethod();// if using is not appropriate
}
}
}
uj5u.com熱心網友回復:
不幸的是,之前發布的所有內容都對我不起作用,或者我只是不明白我必須做什么。
我是 C# 新手,我很難理解技術術語。
但我找到了一個解決方案,使這成為可能。
這不是停止執行緒,而是在執行緒中有函式時停止。
首先在public partial class下設定一個 bool :
public partial class Form1 : Form
{
private volatile bool m_StopThread;
那么你必須在函式中給出你的時間:
while (!m_StopThread)
這意味著您的 while 仍然沒有運行,直到將其設定為 true。
設定好之后,你給你的 Button 或 Timer 一個函式,可能是這樣的:
if ()
{
m_StopThread = true;
}
如果此功能處于活動狀態,您的執行緒將啟動,因為現在它是真的而不是假的。
同樣,您可以通過再次將此功能設定為 false 來再次停止此操作。
如果我正在解釋的解決方案已經被建議,我謝謝你。并希望它對其他人有所幫助。 但不幸的是,我現在無法理解如何進行。
感謝那些每天不遺余力地幫助像我這樣的人的人。:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/447435.html
上一篇:從執行緒函式中獲取值
