如何在另一个函数的函数中停止我的线程?

How to stop my Thread in a function from a other function?

当我的计时器完成时,我需要停止一个线程

但这都是来自其他函数。

我的计时器在按下 Key: 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;
   }                            
}

Idle_Mind 关于如何完成此操作是正确的。下面是一个使用 .NET 6 的工作示例。

一个重要的细节是使用Thread.Join()。这将告诉您的调用者阻塞,直到循环退出并且方法 returns.

这里我使用命令控制台关闭_running标志的切换。你可以用定时器或其他任何东西做同样的事情。请记住,您可能还应该在 class 中使用其中的线程实现 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
        }
    }
}

使用现代方法,你会写出类似

的东西
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;
    }
}

这将使用线程池线程而不是专用线程,并且避免了手动管理计时器的需要。它还可以轻松处理操作的结果,如果有的话。

不幸的是,之前发布的所有内容都不适合我,或者我只是不明白我必须做什么。

我是 C# 新手,我很难理解技术术语。

但我找到了解决方案使这成为可能。

这不是停止线程,而是在线程中有函数时停止。

首先在 public partial class:

的顶部设置一个 bool
    public partial class Form1 : Form
    {
       private volatile bool m_StopThread;

那么你必须在这个函数中给出你的 while:

while (!m_StopThread)

这意味着您的 while 仍然不是 运行,直到它被设置为 true。

设置好后,你给你的按钮或定时器一个功能可能是这样的:

        if ()
        {
            m_StopThread = true;
                            
        }

如果此功能处于活动状态,您的线程将启动,因为现在它是 true 而不再是 false。

同样,您可以通过再次将此函数设置为 false 来再次停止此操作。

如果我正在解释的解决方案已经被建议,我谢谢你。 并希望它能帮助到别人。 但不幸的是,我现在无法理解如何进行。

感谢那些每天都竭尽全力帮助像我这样的人的人。 :)