In C #; What is the most efficient way to check for changes in the background thread?

I create a stream for each of my network communications, and they add answers to the list whenever they hear from the client. I run the task below at runtime to see if there is any connection. It displays the latest on the screen.

Task task = new Task( (() => { int i = 0; while (true) { if (responses.Count > i){ Debug.WriteLine(responses[i]); int index = Form.ActiveForm.Controls.IndexOfKey("responseBox"); Form.ActiveForm.Invoke((MethodInvoker) (() => Form.ActiveForm.Controls[index].Visible = true)); Form.ActiveForm.Invoke((MethodInvoker) (() => Form.ActiveForm.Controls[index].Text = responses[i])); i++; } } })); task.Start(); 

My question is: is there a better way for me to do this? It seems to me wrong that the task is constantly working on something that does not happen very often.

Edit: I am very new to C #, so if there is something obvious, feel free to point it out.

Update:

According to a good MS tutorial related to sidewinder, I added a simple event to the List function add function. like So:

 public delegate void ChangedEventHandler(object sender, EventArgs e); public class listWithChanges<T> : List<T> { public event ChangedEventHandler Changed; protected virtual void OnChanged(EventArgs e) { if (Changed != null) Changed(this, e); } public new void Add (T item) { base.Add(item); OnChanged(EventArgs.Empty); } } 

and added to my output with a delegate

 responses.Changed += ((o, e) => { int index = Form.ActiveForm.Controls.IndexOfKey("responseBox"); Form.ActiveForm.Invoke((MethodInvoker) (() => Form.ActiveForm.Controls[index].Visible = true)); Form.ActiveForm.Invoke((MethodInvoker) (() => Form.ActiveForm.Controls[index].Text = responses[responses.Count - 1])); }); 
+5
source share
2 answers

Events will be a good decision.

An event is an implementation of the Observer template, in which the source (network connection) warn the observers (whoever calls the task in your example), something happened.

This is much more efficient since it does not waste CPU time in an infinite loop; this method is only executed when the client is responding.

C # has excellent support for events, think about how to read the MS Tutorial (originally published by Sidewinder94).

+4
source

If you don’t want to go through a major restructuring of your code, you can use a blocking queue for your responses collection so that your read stream will block while waiting for an element to appear in the queue.

Waiting for something to appear in the blocking queue consumes zero CPU. (Technically different from zero, but invisible nonetheless.)

A quick search gives the following: MSDN - BlockingCollection class

+2
source

All Articles