我创建了以下示例,以了解Task.Factory.FromAsync的用法。根据文档,这样的语法应该可以正常工作,但是除了可以很好地编译外,它总是返回0字节,而内置的ReadAsync可以完美地工作。有谁知道为什么它不像我期望的那样起作用?
class Program
{
static async Task Main(string[] args)
{
var stream = new MemoryStream();
await await Task.WhenAny(
Task.Run(async() => await WriteStream(stream)),
Task.Run(async() => await ReadStream(stream)));
}
private static async Task ReadStream(MemoryStream stream)
{
var buffer = new byte[1024];
while (true)
{
// this version does not work
var read = await Task.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null);
// this version works
// var read = await stream.ReadAsync(buffer,0, buffer.Length);
if(read == 0)
continue;
Console.WriteLine($"bytes read: {read}.");
Console.WriteLine($"message: {Encoding.UTF8.GetString(buffer).Trim((char)0)}.");
Console.WriteLine($"Waiting to receive bytes...");
}
}
private static async Task WriteStream(MemoryStream stream)
{
Console.WriteLine($"Waiting for keyboard input.");
while (Console.ReadLine() is var input && input != "x")
{
var buffer = Encoding.UTF8.GetBytes(input);
await stream.WriteAsync(buffer, 0, buffer.Length);
Console.WriteLine($"Waiting for keyboard input.");
}
}
}