Search code examples
c#.net-4.5async-ctp

NamedPipeServerStream and the await keyword


The article C# Named Pipes with Async, which was written for Async CTP library v3.0, uses code that does not compile with .NET 4.5. Specifically

await pipe.WaitForConnectionAsync();

var message = await streamReader.ReadToEndAsync();

fail because there is no such methods of NamedPipeClientStream.

Did something change in this regard between the CTP and the inclusion in .NET 4.5? Am I missing a step to make this work?


Solution

  • The *Async methods implemented in the Async CTP were temporary extension methods (i.e. they were extension methods that weren't added to the actual classes involved). RTM "moved" those Async methods into the instance methods on the applicable classes. I assume that "move" wasn't as easy as copying the extension methods and some work/testing/acceptance was involved. I'm gathering that some couldn't get moved for various reasons. NamedPipeServerStream.WaitForConnectionAsync seems to be one of those methods. You'll have to use the TaskFactory.FromAsync method to create a Task object from the BeginWaitForConnection/EndWaitForConnection pair to await on. something like:

        await Task.Factory.FromAsync(pipe.BeginWaitForConnection,
            pipe.EndWaitForConnection, null);
        StreamReader reader = new StreamReader(pipe);
        await reader.ReadToEndAsync();