麻烦使用WCF掌握异步模式

时间:2013-10-20 19:45:18

标签: c# .net wcf asynchronous file-transfer

我正在开发一个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;
        }

StateObject:

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上的缓冲区是空的(充满零)。

我不明白我做错了什么,按照我的逻辑,缓冲区应该填充数据,我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

只是预感:您可以在“ServiceStreamReaderStateObject”的Buffer属性中删除“private”访问修饰符

public class ServiceStreamReaderStateObject
{
    public const int BufferSize = 1024;

    public byte[] Buffer { get; set; }

    public int TotalRead { get; set; }

    public ServiceStreamReaderStateObject()
    {
        Buffer = new byte[BufferSize];
    }