c# - Task that ReadsKey from keyboard doesnt work - Consumer/Producer Pattern -
i implementing single producer/consumer pattern using blockingcollection.
when click 'c' keyboard want cancel operation using cancellationtoken.
the strange thing if press 'c' fast can after run program, program listen event.
if click 'c' later lets @ 45000th iteration program doesnt react.
i have loop populates producer.
(int = 0; < 50000; i++) { logger.addtoqueue("number flush " + i, true); } logger.dataitems.completeadding();
at constructor of logger call method:
private task t; public void keypress() { t = task.run(() => { if (console.readkey(true).keychar == 'c') { cts.cancel(); } }); }
i dont know if error relevant other methods post them in case:
the addtoqueue (producer):
public void addtoqueue(string text, bool isflushon) { consumer(isflushon); try { _dataitems.tryadd(new logline() { text = text, timestamp = datetime.now }, 0, ct); } catch (operationcanceledexception) { _dataitems.completeadding(); } }
and consumer:
task task = null; public void consumer(bool isstopwithflushon) { if (task == null) { task = task.run(() => { while (!_dataitems.iscompleted) { try { logline data = null; if (!_dataitems.trytake(out data, 5, ct)) { console.writeline(" take blocked"); } else { stringbuilder stringbuilder = new stringbuilder(); stringbuilder.append(data.timestamp.tostring("yyyy-mm-dd hh:mm:ss:fff")); stringbuilder.append("\t"); stringbuilder.append(data.linetext()); stringbuilder.append("\t"); _writer.writeline(stringbuilder.tostring()); console.writeline(" take:{0}", data.text); } } catch (operationcanceledexception) { if (isstopwithflushon) { console.writeline("canceled flush."); foreach (var dataitem in _dataitems.getconsumingenumerable()) { console.writeline("canceled take:{0}", dataitem.text); stringbuilder stringbuilder = new stringbuilder(); stringbuilder.append(dataitem.timestamp.tostring("yyyy-mm-dd hh:mm:ss:fff")); stringbuilder.append("\t"); stringbuilder.append("number flush " + dataitem.linetext()); stringbuilder.append("\t"); _writer.writeline(stringbuilder.tostring()); thread.spinwait(500000); } } else { console.writeline("canceled without flush."); break; } } } console.writeline("\r\nno more items take."); }); } }
Comments
Post a Comment