Which of these features is more efficient?

When using a thread, "invoke" is used to avoid "Cross Thread" (1)

but sometimes a "timer object" is 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 textBox control - printing data tbxDisplay.Text = bCheckState.ToString(); bCheckState = false; } } } 

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


Maybe there is a problem if we scatter the data processed in the "stream", after checking it in the "timer event", without using the "invoke" or other methods? (We heard that in order to avoid "cross-threading" when printing data processed in a "stream", data scattering in a "timer event" with an additional "timer object" was used quite often, since it is neither useful nor harmful).

+4
source share
2 answers

As Ben Voigt suggested, BackgroundWorker should probably be used here if you have no good reason to want to use something else.

Effective is a rather vague means of comparison. It is not entirely clear what you are looking for in the two options that you are considering.

BackgroundWorker simple and straightforward, and they avoid the use of timers.

Invoke more efficient than a timer in the sense that there will be less delay between bCheckState becoming true and updated text. It will also be less CPU intensive since you will not have a timer polling at a given interval.

Timer more efficient in the sense that the thread does not need to stop when called to update the text, but it is a little inefficient because it will waste processor checking time if the logical value has changed, and there may also be a delay before the timer interval length.

As another alternative, BeginInvoke can be used to update the form without using a timer and without a thread waiting for the call to complete. However, if it throws an exception, your thread may not recognize unless you also call EndInvoke , which will also stop the thread from executing until the call is completed.

All of them have their own advantages and disadvantages, and you cannot really name any particular another “effective” as a whole.

+1
source

Just use the BackgroundWorker instance and handle the ReportProgress and / or RunWorkerCompleted that are already in the correct thread.

+5
source

Source: https://habr.com/ru/post/1391201/


All Articles