使用 WCF 掌握异步模式时出现问题
本文关键字:问题 模式 WCF 掌握 异步 使用 | 更新日期: 2023-09-27 18:36:13
我正在开发一个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
上的缓冲区是空的(充满零)。
按照我的逻辑,缓冲区应该充满数据,我在这里做错了什么?
只是预感:您能否删除"ServiceStreamReaderStateObject"的缓冲区属性上的"私有"访问修饰符
public class ServiceStreamReaderStateObject
{
public const int BufferSize = 1024;
public byte[] Buffer { get; set; }
public int TotalRead { get; set; }
public ServiceStreamReaderStateObject()
{
Buffer = new byte[BufferSize];
}