I am developing a WCF Service on which the server would be capable to make an async call to the client request for specific bytes from a file.
Callback Contract:
public interface IControlChannelCallback
{
[...]
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginGetRemoteFile(string filename, byte[] buffer, int position, int count, AsyncCallback callback, object state);
int EndGetRemoteFile(IAsyncResult ar);
}
Implementation:
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];
}
}
Service Usage:
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);
}
Everything seems to be working, when I call the EndGetRemoteFile
method it returns 1024, which is how many bytes should have been read, but the problem is that the buffer encapsulated on the state object ServiceStreamReaderStateObject
is empty (full of zeros).
I don't understand what I am doing wrong, following by my logic the buffer should be filled with data, what am I doing wrong here?