BackgroundWorker的线程和定时器逻辑 [英] BackgroundWorker thread and Timer logic

查看:380
本文介绍了BackgroundWorker的线程和定时器逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图让我的定时器和BackgroundWorker的线程的逻辑权利。当然我不完全了解整个系统尽管我的阅读。的code以下是摘录有关: 我的投票按钮:

I've been trying to get the logic right for my timer and backgroundworker thread. Granted I don't fully understand the whole system despite all my reading. the following are excerpts of code concerned: My polling button :

private void pollStart_Click(object sender, EventArgs e)
    {
        tst_bgw = new BackgroundWorker();
        //mandatory. Otherwise will throw an exception when calling ReportProgress method  
        tst_bgw.WorkerReportsProgress = true;
        //mandatory. Otherwise we would get an InvalidOperationException when trying to cancel the operation  
        tst_bgw.WorkerSupportsCancellation = true;
        tst_bgw.DoWork += tst_bgw_DoWork;
        tst_bgw.ProgressChanged += tst_bgw_ProgressChanged;
        tst_bgw.RunWorkerCompleted += tst_bgw_RunWorkerCompleted;
        tst_bgw.RunWorkerAsync();

    }

我认为这是正确的,到目前为止

which I think is right so far

我的后台工作线程:

private void tst_bgw_DoWork(object source, DoWorkEventArgs e)
    {
        m_timer = new System.Timers.Timer();
        m_timer.Interval = 1000;
        m_timer.Enabled = true;
        m_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        if (tst_bgw.CancellationPending)
        {
            e.Cancel = true;
            return;
        }

    }

和经过一级事件code:

and the elapsed tier event code:

private void OnTimedEvent(object source, ElapsedEventArgs e)
    {              
        if (powerVal > 3250)
        {
            m_timer.Stop();
            tst_bgw.CancelAsync();
        }
        else
        {
            string pow;                
            int progressVal = 100 - ((3250 - powerVal) / timerVal);
            uiDelegateTest tstDel = new uiDelegateTest(recvMessage);// the recvMessage function takes a textbox as an argument and directs output from socket to it.

            pow = construct_command("power", powerVal); 
            sData = Encoding.ASCII.GetBytes(pow);

            if (active_connection)
                try
                {
                    m_sock.Send(sData);
                    Array.Clear(sData, 0, sData.Length);
                    tstDel(ref unit_Output);// Read somewhere that you can only modify UI elements in this method via delegate so I think this is OK.
                    m_sock.Send(time_out_command);
                    tstDel(ref unit_Output);
                    tst_bgw.ReportProgress(progressVal);
                }
                catch (SocketException se)
                {
                    MessageBox.Show(se.Message);
                }
            tst_bgw.ReportProgress(powerVal, progressVal);
            powerVal = powerVal + pwrIncVal;
        }

我只是想知道一些其他的东西;我使用的是正确的定时器(不,我认为它应该极大地重要,但有人认为,这可能是我想要做的最好的定时器)和卡尼真的只有通过代表修改的DoWork的方法UI元素,如果是的有sepcial考虑这样做。 很抱歉的长帖子,感谢您的时间。

I'd just like to know a few other things; am I using the right timer (not that I think it should matter greatly but it was suggested that this might be the best timer for what I want to do) and canI really modify UI elements in the DoWork method only through delegates and if yes are there sepcial considerations to doing so. Sorry about the long posting and thank you for your time.

推荐答案

有很多不对的code。

There is lots wrong with this code.

1)你是不是处理你的背景工人。 BackgroundWorkers必须在使用后废弃的。它们被设计成用作的winforms组件和通常将经由设计者添加到窗口。这将确保将其与表单创建和布置时的形式是。
2)所有你在做你的DoWork方法是创建一个新的计时器,并运行它。没有一点做这在后台工作,因为它会这么快发生反正。
3)你将在每次你再次运行后台工作的时间重新计时。但你永远不会停止或处置旧定时器,你只是覆盖的成员。

1) You aren't disposing of your background worker. BackgroundWorkers must be disposed of after use. They are designed to be used as winforms components and would normally be added to a window via the designer. This will ensure it is created with the form and disposed of when the form is.
2) All you are doing in your dowork method is creating a new timer and running it. There is no point of doing this in a background worker because it will happen so quickly anyway.
3) You will recreate the timer every time you run the background worker again. But you aren't ever stopping or disposing of the old timer, you are just overwriting the member.

我建议你摆脱BackgroundWorker的完全,只使用一个计时器。创建于形式的构造函数的计时器,并确保您的形式处置,处置的方法。 (或使用设计器将它添加到窗体)。在pollstart_click方法只是开始计时。 (如果你有一个民意调查止损方法,你可以停止计时器)

I recommend you get rid of the BackgroundWorker completely and just use a timer. Create the timer in the forms constructor and make sure you dispose of it in the forms dispose method. (Or use the designer to add it to the form). In the pollstart_click method just start the timer. (If you have a poll stop method, you can stop the timer in that)

这篇关于BackgroundWorker的线程和定时器逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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