c# - Implementing async timeout using poor mans async/await constructs in .Net 4.0 -
motivation
c# 5.0 async/await constructs awesome, unfortunately yet microsoft shown release candidate of both .net 4.5 , vs 2012, , take time until these technologies adopted in our projects.
in stephen toub's asynchronous methods, c# iterators, , tasks i've found replacement can nicely used in .net 4.0. there dozen of other implementations make possible using approach in .net 2.0 though seem little outdated , less feature-rich.
example
so .net 4.0 code looks (the commented sections show how done in .net 4.5):
//private async task processmessageasync() private ienumerable<task> processmessageasync() { //var udpreceiveresult = await udpclient.receiveasync(); var task = task<udpasyncreceiveresult> .factory .fromasync(udpclient.beginreceive, udpclient.endreceive, null); yield return task; var udpreceiveresult = task.result; //... blah blah blah if (message bootstraprequest) { var typedmessage = ((bootstraprequest)(message)); // !!! .net 4.0 has no overload cancellationtokensource // !!! takes timeout parameter :( var cts = new cancellationtokensource(bootstrapresponsetimeout); // error here //... blah blah blah // say(messageipendpoint, responsemessage, cts.token); task.factory.iterate(say(messageipendpoint, responsemessage, cts.token)); } }
looks little ugly though job
the question
when using cancellationtokensource in .net 4.5 there constructor takes timespan timeout parameter, resulting cancellationtokensource
cancels within specified period of time.
.net 4.0 not able timeout, correct way of doing in .net 4.0?
does have async/await? looks you're needing way cancel token, independently of async/await, right? in case, create timer calls cancel after timeout?
new timer(state => cts.cancel(), null, bootstrapresponsetimeout, timeout.infinite);
edit
my initial response above basic idea, more robust solution can found in is cancellationtokensource.cancelafter() leaky? (actually .net 4.5 implementation of constructor you're seeking). here's function can use create timeout tokens based on code.
public static cancellationtokensource createtimeouttoken(int duetime) { if (duetime < -1) { throw new argumentoutofrangeexception("duetime"); } var source = new cancellationtokensource(); var timer = new timer(self => { ((timer)self).dispose(); try { source.cancel(); } catch (objectdisposedexception) {} }); timer.change(duetime, -1); return source; }
Comments
Post a Comment