开发者

How to pass values between threads?

开发者 https://www.devze.com 2023-01-18 05:26 出处:网络
I have a windows forms program with a form MainForm. On a button press I start a code that runs (pulses) on every 0.5secs on another thread. I want to modify many things, like label开发者_Go百科s, pro

I have a windows forms program with a form MainForm. On a button press I start a code that runs (pulses) on every 0.5secs on another thread. I want to modify many things, like label开发者_Go百科s, progressbars on my MainForm, from the Pulse method. How is this possible? So I would like to know, how to interract with variables, values, in that thread, and the MainForm. Modify each other, etc..

On foo button click, I tell my pulsator to start. Pulsator.Initialize();

Here is the Pulsator class:

public static class Pulsator
{
    private static Thread _worker;

    public static void Initialize()
    {
        _worker = new Thread(Pulse);
        _worker.IsBackground = true;
        _worker.Start();
    }

    public static void Close()
    {
        if (_worker != null)
        {
            _worker.Abort();
            while (_worker.IsAlive || _worker.ThreadState != ThreadState.Stopped)
            {
               //closing
            }
        }
    }

    public static void Pulse()
    {
        if (_worker != null)
        {
            while (true)
            {
                SomeOtherClass.Pulse();
                Thread.Sleep(500);
            }
        }
        else
        {
            SomeOtherClass.Pulse(); // yeah I know this doesnt needed
        }
    }
}

SomeOtherClass Pulse method looks like :

    public static void Pulse()
    {
        //here I will have several values, variables, and I want to show results,
        // values on my MainForm, like:
        Random random = new Random();
        MainForm.label1.Text = random.Next(123,321).ToString(); // I hope you know what I mean
    }

Of course it's much complicated, it's just a silly example.


Generally, in WinForms it's not safe to modify the state of visual controls outside the thread that owns the control's underlying unmanaged resources (window handle). You have to use the Control.Invoke method to schedule executing the modification on the control's owning thread.


As others already mentioned, you have to use Control.Invoke to change the UI controls from the background thread.

Another option is to use System.ComponentModel.BackgroundWorker (it's available in the form designer toolbox). You could then take a regular forms timer, to call the RunWorkerAsync-Method and do your background work in the DoWork event handler, which is automatically called from another thread.

From there, you can hand data back to the main thread, by calling ReportProgress. This will raise the ProgressChanged event in the main thread, where you are free to update all your UI controls.


Why not use a System.Timers.Timer?

E.g.:

        trainPassageTimer = new Timer(500);
        trainPassageTimer.AutoReset = true;
        trainPassageTimer.Elapsed += TimeElapsed;

        ...

        private void TimeElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
// Do stuff
// Remember to use BeginInvoke or Invoke to access Windows.Forms controls
        }


C# 2 or higher (VS2005) has anonymous delegates (and C# 3 has lambdas which are a slightly neater version of the same idea).

These allow a thread to be started with a function that can "see" variables in the surrounding scope. So there is no need to explicitly pass it anything. On the downside, there is the danger that the thread will accidentally depend on something that it should not (e.g. a variable that is changing in other threads).

_worker = new Thread(delegate 
{
    // can refer to variables in enclosing scope(s).
});
0

精彩评论

暂无评论...
验证码 换一张
取 消