c# - Queued Method invocation in its own thread -
maybe functionality buried somewhere in .net-framework couldn't find it. need execute methods in given order, 1 after one. methods should return (e.g. object), there way react returned data (e.g. cancel execution of following methods because error occurred). execution of methods should run in own thread , should able add methods queue @ time. idea how implement in c#?
thanks jon's comment tried implement such queue on me own. might completly wrong - comments welcome ;-)
using system; using system.collections.concurrent; using system.threading.tasks; namespace functionqueue { public class errorresult { public string errormessage { get; set; } public bool cancelqueue { get; set; } } public class functionqueue { private readonly concurrentqueue<func<object>> queue; private bool isexecuting; private bool iscanceled; private readonly action<errorresult> onerror; private readonly action oncomplete; public functionqueue(action<errorresult> onerror = null, action oncomplete = null) { this.queue = new concurrentqueue<func<object>>(); this.onerror = onerror; this.oncomplete = oncomplete; } public void addfunctiontoqueue( func<object> functiontoadd, bool startqueue = false ) { this.queue.enqueue(functiontoadd); if (startqueue && !this.isexecuting) this.processqueue(); } public void processqueue() { if( this.queue.count > 0 ) { task.run( () => { this.iscanceled = false; this.isexecuting = true; func<object> functiontoexecutenext; while( !iscanceled && this.queue.trydequeue( out functiontoexecutenext ) ) { object result = functiontoexecutenext(); errorresult errorresult = result errorresult; if( errorresult != null ) { if( this.onerror != null ) this.onerror( errorresult ); if( errorresult.cancelqueue ) this.iscanceled = true; } } } ); } this.isexecuting = false; if( this.oncomplete != null ) this.oncomplete(); } } }
i add feature unfortunately have no idea how implement this: add optional callback every added function. callback should called when given function completed. how can add feature?
sounds use producer/consumer queue of func<object>
.
assuming you're using .net 4, should use blockingcollection<t>
wrapper around appropriate iproducerconsumercollection<t>
(e.g. concurrentqueue<t>
). these types designed make producer/consumer situations easy.
you should @ dataflow provides higher-level constructs on top of this, if need build pipeline example.
Comments
Post a Comment