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

C# 循环触发自定义事件的错误

2011-12-31 
C# 循环触发自定义事件的异常在类中自定义事件.并在类的方法中根据实际需要循环触发该事件.用debug跟踪,结

C# 循环触发自定义事件的异常
在类中自定义事件.
并在类的方法中根据实际需要循环触发该事件.
用debug跟踪   ,结果发现:
循环触发的事件的次数=(2+循环次数)   *   循环次数   /2
即循环时,第一次触发1次
                      二             2
                        .             .
                        .             .
                        .             .
                        n             n

不知道如何解决该问题.何向各个大侠求救.
代码如下
自定义类
        class   Class1
        {
                public   Class1()
                {
                }
                public   delegate   void   test(int   index,int   count);
                public   event   test   testEvent;
                public   void   Client()
                {
                        //循环触发事件,测试用
                        for   (int   i   =   0;   i   <=   10;   i++)
                        {
                                testEvent(i+1,10);
                        }
                }
        }
-------------------------------------
调用该类的窗体
        public   partial   class   Form1   :   Form
        {
                private   Class1   cls;
                public   Form1()
                {
                        InitializeComponent();
                        cls   =   new   Class1();
                        cls.testEvent   +=   new   Class1.test(cls_testEvent);
                }

                void   cls_testEvent(int   index,   int   count)
                {
                        Trace.Listeners.Add(new   TextWriterTraceListener(Console.Out));
                        Trace.AutoFlush   =   true;


                        Trace.WriteLine(index.ToString()   +   "       "   +   count.ToString());

                        this.progressBar1.Value   =   (int)(index   /   count   *   100);

                }

                private   void   button1_Click(object   sender,   EventArgs   e)
                {
                        cls.Client();
                }
        }

[解决办法]
多线程操作ui,用异步
[解决办法]
Thread.Sleep(100)
让界面重绘。
建立界面线程,专门更新界面

热点排行