views:

112

answers:

6

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 labels, 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); // Roughly 30FPS
            }
        }
        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, bad code :)

A: 

try this http://www.dotnetforce.com/Content.aspx?t=a&n=220

Aamod Thakur
This does not answer his question. If you read the entire question you would see that he's asking how to pass data from one running thread to another running thread.
Lasse V. Karlsen
Lasse Karlsen, you're correct :/ Thanks anyways :)
Dominik
A: 

If you are using .net 2.0 or higher version , you can use ThreadStartDelegate which is designed by Microsoft to send parameters to a thread.

For updating UI control , that would not be possible on a secondary thread because Main Thread Created your UI control , try to utilize control.IsInvokeRequired property.

saurabh
I think he's asking how to pass data from that other thread to his GUI thread. At least mention (and link to) the Invoke method on Control. IsInvokeRequired is not nearly enough.
Lasse V. Karlsen
+4  A: 

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.

Ondrej Tucny
A: 

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).
});
Daniel Earwicker
Will take a look at it, thank you.
Dominik
+1  A: 

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
        }
Holstebroe
Will take a look :) Looks the best sln so far.
Dominik
System.Windows.Forms.Timer would be a better choice for doing UI work: http://msdn.microsoft.com/msdnmag/issues/04/02/TimersinNET/default.aspx
Wayne
+1  A: 

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.

Gnafoo