如何停止循环(C#)

来源:百度知道 编辑:UC知道 时间:2024/05/29 20:40:38
假如按下button1后,启动一个新线程,并在这个线程中执行一个循环。我想在按下button2后,停止此循环。我在button2中已经设定了相关的代码,并设置了全局变量,让循环判断是否继续执行循环。但关键的问题是,再按下button1后,其它所有的按键都死掉了,按上没反映。Delphi中有个Application.ProcessMessage()可以有,C#中有没有什么好方法?

你可以这样啊:
建立一个线程.让一切操作在那个线程中运行包括执行死循环.
主线程则随时调用那个线程的挂起方法.
Abort();

你要是单线程死循环操作控件的话那.........
程序假死是肯定的了.
但是用多线程操作控件,那么你就要在你那个窗体的加载时先为那个窗体对象的一个静态属性赋值:
Form1.CheckForIllegalCrossThreadCalls = false;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace dietest1
{
public partial class Form1 : Form
{
System.Threading.Thread threadToPlay;
public Form1()
{
InitializeComponent();
Form1.CheckForIllegalCrossThreadCalls = false;
}

void Go()
{
System.Threading.ThreadStart ts = new System.Threading.ThreadStart(die);
threadToPlay = new System.Threading.Thread(ts);
thre