Implementing callback mechanism as async/await pattern in C# -
how transform following callback-driven code async/await pattern properly:
public class devicewrapper { // external device provides real time stream of data private internaldevice device = new internaldevice(); private list<int> accumulationbuffer = new list<int>(); public void startreceiving() { // following callback invocations might synchronized main // ui message pump, particular window message pump // or other way device.synchronization = synchronization.ui; device.dataavailable += dataavailablehandler; device.receivingstoppedorerroroccured += stophandler; device.start(); } private void dataavailablehandler(object sender, dataeventargs e) { // filter data e.data , accumulate accumulationbuffer field. // if certail condition met, signal pending task (if there any) //as complete return awaiting caller accumulationbuffer or perhaps temporary buffer created accumulationbuffer // in order make available caller. // handle requested cancellation. } public task<byte[]> getdata(cancellationtoken token) { // create task returning data filtered , accumulated in dataavailablehandler } } // usage: async void test() { devicewrapper w = new devicewrapper(); w.startreceiving(); while(true) { byte[] filtereddata = await w.getdata(cancellationtoken.null); use(filtereddata); } }
i have sought inspiration solve reading .net streamreader class source, made me more confused.
thank experts advice!
you're looking taskcompletionsource<byte[]>
. approximation of like:
public task<byte[]> getdata(cancellationtoken token) { cancellationtoken.throwifcancellationrequested; var tcs = new taskcompletionsource<byte[]>(); dataeventhandler datahandler = null; datahandler = (o, e) => { device.dataavailable -= datahandler; tcs.setresult(e.data); } stopeventhandler stophandler = null; stophandler = (os, se) => { device.receivingstoppedorerroroccured -= stophandler; // assuming stop handler has sort of error property. tcs.setexception(se.exception); } device.dataavailable += datahandler; device.receivingstoppedorerroroccured += stophandler; device.start(); return tcs.task; }
Comments
Post a Comment