从(System.Timer)Timer事件访问进度栏将给出“跨线程操作无效" [英] Accessing a Progress bar from (System.Timer)Timer Event gives "Cross-Thread Operation Not Valid)

查看:137
本文介绍了从(System.Timer)Timer事件访问进度栏将给出“跨线程操作无效"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一种表格,其中必须在同时执行操作的同时增加进度条(换句话说,我正在显示此操作的进度). 此操作需要50秒钟.因此,我使用了System.Timer来增加进度栏.

我的代码中没有一个线程.当我在计时器事件处理程序中编写Progress_bar.PerformStep()时,它给出错误,例如跨线程操作无效".

[根据此错误,我分析了System.Timer必须正在创建线程并在其中运行计时器以执行多个任务.]

每秒我应该怎样增加进度条?

我尝试了解决方案

听起来您正在主线程上执行后台"操作,这就是为什么进度条在调用时不会更新的原因. /p>

请查看 BackgroundWorker .

>

I am designing a form in which I have to increase a Progress bar while an operation is being performed simultaneously (In other words, I am showing the progress of this operation). This operation takes 50 seconds. So I have used a System.Timer to Increase the Progress bar.

There isn't a single thread in my code. When I write Progress_bar.PerformStep() in Timer Event Handler, it gives error as "Cross Thread Operation Not Valid".

[From this error I analyzed that System.Timer must be creating a Thread and Runs the timer in it to perform multiple tasks.]

What should I do to increase my progress bar after every Second?

I tried solution given in this question. It removed the error but Now I can't see the progress bar increasing. Means it Starts.... No Increase for 50 sec and after it 100%.

Code is as follows:

Timer Declaration (It is Global):

public System.Timers.Timer Thetimer = new System.Timers.Timer(1000);

Event Declaration (This is in Constructor to make it...err...Public [May not be a correct word]):

Thetimer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);

Call:

 Thetimer.Start();

 blRetVal = FunctionToBeExecuted(parameter);

 Thetimer.Stop();

Event Handler:

 void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
           //StatusBar.PerformStep();  -- Tried This. It gives the Error

/* This doesn't give an error but Another issue Arises */

            if (InvokeRequired)
            {
                BeginInvoke(new Action(StatusBar.PerformStep));

            }
            else
                StatusBar.PerformStep();
        }

P.S. I am using C# and Visual Studio 2008

解决方案

It sounds like you're performing your "background" operation on the main thread, which is why your progress bar doesn't update when you invoke it.

Have a look at BackgroundWorker.

这篇关于从(System.Timer)Timer事件访问进度栏将给出“跨线程操作无效"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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