首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

中断for循环有关问题

2012-05-20 
中断for循环问题我想用一个按钮,点击后中断for循环。能不能让程序运行的时候有单步调试的功能,点一个按钮后

中断for循环问题
我想用一个按钮,点击后中断for循环。
能不能让程序运行的时候有单步调试的功能,点一个按钮后可以执行下一句语句。

[解决办法]
1. 首先制作一个类似DoEvent的类
2. 设置一个全局Bool变量
3. for循环中调用DoEvent判断全局Bool变量,如果是true就进入等待(一直DoEvent)
4. 按钮点击事件改编全部Bool变量


DoEvent类
public static class DispatcherHelper
{
/// <summary>
/// Simulate Application.DoEvents function of <see cref=" System.Windows.Forms.Application"/> class.
/// </summary>
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static void DoEvents()
{
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
new DispatcherOperationCallback(ExitFrames), frame);

try
{
Dispatcher.PushFrame(frame);
}
catch (InvalidOperationException)
{
}
}
/// <summary>
///
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
private static object ExitFrames(object frame)
{
((DispatcherFrame)frame).Continue = false;

return null;
}
}
[解决办法]

C# code
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Threading;namespace WindowsApplication1{         public partial class Form1 : Form    {        private AutoResetEvent _SendEvent = null;        public Form1()        {            InitializeComponent();            _SendEvent = new AutoResetEvent(false);        }        private void button1_Click(object sender, EventArgs e)        {            ThreadStart oh=new ThreadStart (_send);            Thread thread = new Thread(oh);            thread.Start();        }        private void button2_Click(object sender, EventArgs e)        {            _SendEvent.Set();        }        private void _send()        {            for (int index = 0; index < 10; index++)            {                _SendEvent.WaitOne();                MessageBox.Show("Hello!");                _SendEvent.WaitOne();                MessageBox.Show("Bye");                ……            }        }    }} 

热点排行