我正在开发一个 WCF 服务,在该服务上,服务器能够对来自文件的特定字节的客户端请求进行异步调用。
回调合约:
public interface IControlChannelCallback
{
[...]
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginGetRemoteFile(string filename, byte[] buffer, int position, int count, AsyncCallback callback, object state);
int EndGetRemoteFile(IAsyncResult ar);
}
执行:
public IAsyncResult BeginGetRemoteFile(string filename, byte[] buffer, int position, int count, AsyncCallback callback,
object state)
{
var task = Task<int>.Factory.StartNew(x =>
{
using (var fileStream = new FileStream(filename, FileMode.Open))
{
fileStream.Position = position;
return fileStream.Read(buffer, 0, count);
}
}, state);
return task.ContinueWith(x => callback(task));
}
public int EndGetRemoteFile(IAsyncResult ar)
{
var task = (Task<int>) ar;
return task.Result;
}
状态对象:
public class ServiceStreamReaderStateObject
{
public const int BufferSize = 1024;
public byte[] Buffer { get; private set; }
public int TotalRead { get; set; }
public ServiceStreamReaderStateObject()
{
Buffer = new byte[BufferSize];
}
}
服务使用:
private void Download()
{
var state = new ServiceStreamReaderStateObject();
_client.Callback.BeginGetRemoteFile(@"F:\1313363989488.jpg", state.Buffer, 0, state.Buffer.Length, RealCallback, state);
}
private void RealCallback(IAsyncResult ar)
{
var state = (ServiceStreamReaderStateObject) ar.AsyncState;
var totalRead = _client.Callback.EndGetRemoteFile(ar);
}
一切似乎都在工作,当我调用该EndGetRemoteFile
方法时,它返回 1024,这是应该读取多少字节,但问题是封装在状态对象上的缓冲区ServiceStreamReaderStateObject
是空的(全是零)。
我不明白我做错了什么,按照我的逻辑缓冲区应该充满数据,我在这里做错了什么?