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])); });
source share