如何在按下按钮启动线程并停止它,如果再次按下? [英] How to start thread if button pressed and stop it if pressed again?

查看:245
本文介绍了如何在按下按钮启动线程并停止它,如果再次按下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的代码做什么我所要求的:

I'm using the next code to do what I'm asking for :

private delegate void CallerDelegate(object e);
CallerDelegate caler = new CallerDelegate(MethodToCall);



按钮单击事件:

on button click event :

if (currBusyThrd != null && currBusyThrd.IsAlive)
   {
    currBusyThrd.Abort();
   }
ThreadPool.SetMaxThreads(1, 1);
//queue the work for thread processing
ThreadPool.QueueUserWorkItem(new WaitCallback(WaitCallbackMethod))


$ B工作$ b

WaitCallbackMethod方法是:

"WaitCallbackMethod" Method is :

void WaitCallbackMethod(object stateInfo)
  {
     // argList : i put some argument in a list to use it in "MethodToCall" ...
     BeginInvoke(caler,argList);
  }

和我被线程调用的方法是:

and the method i'm calling by the thread is :

void MethodToCall(object args)
 {
 //Here I get the thread I'm calling to stop it when btn clicked again
 currBusyThrd = Thread.CurrentThread;

 // The rest of the code ...
 }



其余

我觉得这是不对的......
如何做是正确的?

I feel that this is wrong ... How to do it right ?

实际上调用将是TextBox_KeyUp ..所以每次用户输入一个字符代码将再次..和BackgroundWorker的不工作执行。

Actually the calling will be by TextBox_KeyUp .. so every time the user enter a char the code will execute again .. and the BackgroundWorker didn't work .

推荐答案

一个问题这种方法是它的非常危险擅自中止一个线程(在几乎任何语言)。有可以弹出各地unfreed资源和misheld锁的问题太多。这是典型的最好设置某种标志的要求线程安全地中止自己或有关线程忘记,让它运行完毕。

One problem to this approach is that it's very dangerous to arbitrarily Abort a thread (in pretty much any language). There are too many issues that can popup around unfreed resources and misheld locks. It's typically best to set some kind of flag to ask the Thread to safely abort itself or to forget about the thread and let it run to completion.

此外,在线程池中止线程是很危险的,我相信没有一个支持的操作。 ThreadPool中的线程是不属于你和他们中止冷对线程池严重影响。

Additionally, Aborting a Thread in the ThreadPool is very dangerous and I believe not a supported operation. The Threads in the ThreadPool are not owned by you and Aborting them cold have serious implications for the ThreadPool.

下面是我想借此解决方案。

Here is the solution I would take.

private object m_lock = new object();
private bool m_isRunning = false;
private bool m_isAbortRequested = false;

public void OnButtonClick(object sender, EventArgs e) {
  lock ( m_lock ) {
    if ( m_isRunning ) {
      m_isAbortRequested = true;
    } else {
      m_isAbortRequested = false;
      m_isRunning = true;
      ThreadPool.QueueUserWorkItem(BackgroundMethod);
    }
  }
}

private void BackgroundMethod() {
  try {
    DoRealWork();
  } finally {
    lock (m_lock) {
      m_isRunning = false;
    }
  }
}

private void DoRealWork() {
  ...
  if ( m_isAbortRequested ) {
    return;
  }
}

这篇关于如何在按下按钮启动线程并停止它,如果再次按下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆