Motivation
The C # 5.0 async / await scripts look amazing, but unfortunately, Microsoft will only show a candidate for both .NET 4.5 and VS 2012, and it will take some time until these technologies are widely adopted in our projects.
In Stephen Toub Asynchronous Methods, C # Iterators, and Tasks I found a replacement that can be used well in .NET 4.0. There are a dozen other implementations that allow you to use the approach even in .NET 2.0, although they seem a bit outdated and less feature rich.
Example
So, now my .NET 4.0 code looks like (in the comments sections show how this is 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 is BootstrapRequest) { var typedMessage = ((BootstrapRequest)(message)); // !!! .NET 4.0 has no overload for CancellationTokenSource that // !!! 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)); } }
It looks a little ugly, although it does the job
Question
When using CancellationTokenSource in .NET 4.5, there is a constructor that takes a period of time as a timeout parameter, so that the result of CancellationTokenSource
is canceled for a certain period of time.
.Net 4.0 cannot time out, so what is the correct way to do this in .Net 4.0?
source share