I'm trying to implement the progress notification mechanism when copying files. I'm doing this in the following way:
- I create two FileStreams - for reading and writing
- Call the BeginRead passing to it a ReadCallback and a structure containing the reading stream and the array to fill with the data read from a file.
- In the ReadCallback I call the EndRead method and call the BeginWrite method on the file stream used for writing passing to it a WriteCallback and a structure containing the stream (used for writing) and the array to write (the same as with the reading part).
- When I call the EndWrite in the WriteCallback passing to it the asyncResult it throws an ArgumentException: Either the IAsyncResult object did not come from the corresponding async method on this type, or EndRead was called multiple times with the same IAsyncResult
Please help to resolve this.
Update Source code:
private void StartAsyncCopying()
{
var sourceFileInfo = new FileInfo(Source);
if (!sourceFileInfo.Exists)
{
throw new FileNotFoundException("File not found.",
Source);
}
m_sourceLength = sourceFileInfo.Length;
m_readerStream = new FileStream(Source, FileMode.Open);
m_writerStream = new FileStream(Target, FileMode.Create);
m_queueBuffer = new Queue<byte[]>(DefaultQueueBufferSize);
m_queueBufferLock = new object();
ProgressRead();
}
private void ProgressRead()
{
var readerChunck = new byte[DefaultChunckSize];
var streamChunck = new StreamChunck(readerChunck, m_readerStream);
m_readerStream.BeginRead(streamChunck.Chunck,
0,
streamChunck.Chunck.Length,
ReadCallback,
streamChunck);
}
private void ReadCallback(IAsyncResult asyncResult)
{
var streamChunck = asyncResult.AsyncState as StreamChunck;
var numberOfBytesRead = streamChunck.Stream.EndRead(asyncResult);
m_readerOffset += numberOfBytesRead;
ProgressWrite(streamChunck.Chunck);
}
private void ProgressWrite(byte[] chunck)
{
var streamChunck = new StreamChunck(chunck, m_writerStream);
m_writerAsyncResult = m_writerStream.BeginWrite(streamChunck.Chunck,
0,
streamChunck.Chunck.Length,
WriteCallback,
streamChunck);
}
private void WriteCallback(IAsyncResult asyncResult)
{
var streamChunck = asyncResult.AsyncState as StreamChunck;
var numberOfBytesWritten = streamChunck.Stream.EndRead(asyncResult);
m_writerOffset += numberOfBytesWritten;
var progressChangedEventArgs = new CopyProgressChangedEventArgs(m_operationDescription,
m_sourceLength,
m_writerOffset);
OnCopyProgressChanged(progressChangedEventArgs);
if (m_writerOffset == m_sourceLength)
{
var copyCompletedEventArgs = new CopyCompletedEventArgs(m_operationDescription, null);
OnCopyCompleted(copyCompletedEventArgs);
}
else
{
ProgressRead();
}
}