c# - Wait for Collection to be Updated -
i need bit of code wait item added collection. thread needs wait until completes before continues. item gets added collection thread (kicked off elsewhere), , have no way signal current thread has occurred.
a naive implementation might (ignoring thread safety on collection, etc. now):
public static list<string> mylist = new list<string>(); public void waitingmethod(string id) { bool waiting = true; while (waiting) { int index = mylist.indexof(id); if (index >= 0) { waiting = false; } } //thread continues here }
i believe block thread , peg processor.
what more efficient way achieve this?
could instead use observable collection, , subscribe collectionchanged event?
namespace consoleapplication3 { using system; using system.collections.objectmodel; using system.linq; using system.threading; using system.threading.tasks; internal class program { private static readonly observablecollection<string> mylist = new observablecollection<string>(); private static autoresetevent resetevent = new autoresetevent(false); private static void main(string[] args) { task.factory.startnew( () => { (int = 0; < 10; i++) { string item = i.tostring("0000"); mylist.add(item); console.writeline(item); thread.sleep(1000); } }); mylist.collectionchanged += (sender, eventargs) => { if (eventargs.newitems.cast<string>().any(a => a.equals("0005"))) resetevent.set(); }; resetevent.waitone(); } } }
here how can control loop generating items being added collection:
namespace consoleapplication3 { using system; using system.collections.objectmodel; using system.linq; using system.threading; using system.threading.tasks; internal class program { #region static fields private static readonly cancellationtokensource cts = new cancellationtokensource(); private static readonly observablecollection<string> mylist = new observablecollection<string>(); private static readonly autoresetevent resetevent = new autoresetevent(false); #endregion #region methods private static void main(string[] args) { task task = task.factory.startnew( () => { (int = 0; < 10 && !cts.iscancellationrequested; i++) { string item = i.tostring("0000"); mylist.add(item); console.writeline(item); thread.sleep(100); } }, cts.token); task finish = task.continuewith(antecedent => { console.writeline("task finished. status {0}", antecedent.status); }); mylist.collectionchanged += (sender, eventargs) => { if (eventargs.newitems.cast<string>().any(a => a.equals("0005"))) { cts.cancel(); resetevent.set(); } }; resetevent.waitone(); task.waitall(finish); } #endregion } }
Comments
Post a Comment