multithreading - Asynchronous calling mechanism design c# -
the requirement continuosly read data hardware , send data upper layers further processing.
presently use synchronous mechanism. i.e request --> wait --> read ---> send processing.
{ int ix = iy; iy = 0; if(ix<1) { while (((ix = readsst(ref sbuffer)) < 1) && bprocessnotended == true) { if (ix < 0) // bt error { eerr = cerror.buff_kill; //throw error , exit break; } thread.sleep(2); itimeout += 2; if (itimeout > timeout_2000) { eerr = cerror.timeout_err; objlogger.writeline("hw timed out"); break; } } } ibytesread = ix; if (ibytesread <= 0) { eerr = cerror.read_err; objlogger.writeline("read error"); break; } sreadmsg = sreadmsg + sbuffer; if(sreadmsg.length >0) iendpos = sreadmsg.indexof('\n',1); else iendpos = -1; if (sreadmsg.length > 2) { if ((iendpos == 0 && sreadmsg[0] == '\n') || (iendpos > 0 && sreadmsg[sreadmsg.length - 1] == '\n' && sreadmsg[sreadmsg.length - 2] == '\r')) //finished { thread.sleep(50); // wait short time sure there there no further input if (sreadmsg.length >= 3 && sreadmsg[sreadmsg.length - 3] == 'a') continue; iy = readsst(ref sbuffer); if (iy == 0) { bprocessnotended = false; objlogger.writeline("bprocessnotended made false, end of frame detected"); break; } else if (iy < 0) { eerr = cerror.buff_kill; // error break; } } } } while (bprocessnotended);
the readsst method call made hardware request data.
as seen code, present logic loop , read till bprocessnotended flag true. once end of frame detected in string buffer receive, set flag false , looping stopped (so reading hardware)
now need achieve parallelism in code boost performance want learn improve in way reading done in asynchronous fashion.
anyone out there who's gonna me in improving existing design.
thanks in advance
generally there 3 common patterns asynchronous work in .net:
- the asynchronous programming model
- the event-based asynchronous programming model
- the task parallel library (.net 4.0)
for low-level piece of code go 1 or 3, 2 used on higher level components.
the general design go execute loop in separate thread using of above ways , when loop finished notifying calling thread operation completed, passing result (in case should content of sreadmsg
) in appropriate way (depends on way choose).
here short example on how using tpl:
private void readmessageasync() { // set task read message hardware device. task<string> readmessagetask = new task<string>(readmessage); // set task process message when message read device. readmessagetask.continuewith(processmessage); // start task asynchronously. readmessagetask.start(); } private void processmessage(task<string> readmessagetask) { string message = readmessagetask.result; // process message } private string readmessage() { string message = string.empty; // retrieve message using loop return message; }
Comments
Post a Comment