Which of these functions is the more effective one?

269 views Asked by At

When using the thread, 'invoke' is being used to avoid 'Cross Thread'(1)

but, sometimes 'timer object' is being used to avoid 'CrossThread' (2)

like this(for example)

public partial class Form1 : Form
{

    private bool bCheckState = false;

    public Form1()
    {
        InitializeComponent();
    }

    //Button Click
    private void btnWork_Click(object sender, EventArgs e)
    {
        Thread m_Thread = new Thread(new ThreadStart(Work));
        m_Thread.Start();

    }

    private void Work()
    {
        bCheckState = true;            
        // not use invoke 
    }


    private void timer_Tick(object sender, EventArgs e)
    {
        if (bCheckState)
        {
            //tbxDisplay is winform's textBox control - printing data
            tbxDisplay.Text = bCheckState.ToString();
            bCheckState = false;
        }
    }
}

which one is more effective? 'between (1) and (2)'


Could it be a problem if we scatter the data processed within 'thread' after checking it in the 'timer event', without using 'invoke' or other methods? (We heard that to avoid 'Cross-Thread' when printing the data processed within 'thread', scattering the data in the 'timer event' with additional 'timer object' has been used quite often as it is neither beneficial nor harmful).

2

There are 2 answers

0
William Lawn Stewart On BEST ANSWER

As Ben Voigt suggested, a BackgroundWorker is probably what you should be using here, unless you have a good reason to want to use something else.

"Effective" is a rather vague means of comparison. Its not entirely clear what you're looking for in the two options you are considering.

BackgroundWorkers are simple and easy to understand, and they avoid the use of timers.

Invoke is more effective than a timer in the sense that there will be less of a delay between bCheckState becoming true and the text being updated. It will also be less CPU-intensive, since you won't have a timer polling at a set interval.

The Timer is more effective in the sense that the thread won't have to stop while invoking to update the text, but it is a bit inefficient because it is going to waste CPU time checking if the boolean has changed, and there could also be a delay of up to the timer interval length before the form changes.

As another alternative, BeginInvoke could be used to update the form without the use of a timer, and without the thread having to wait for the invoke to complete. However, if it raises an exception, your thread might not find out unless you also then call EndInvoke, which will also halt execution of the thread until the invoke is complete.

They all have their advantages and disadvantages, and you can't really call any particular one more "effective" in general.

0
Ben Voigt On

Just use a BackgroundWorker instance and handle the ReportProgress and/or RunWorkerCompleted events, which are already in the right thread.