关于Parallel.For和Lock

时间:2014-12-06 06:49:37

标签: c# .net parallel-processing

if (File.Exists(copypath)) File.Delete(copypath);

using (FileStream inputstream = new FileStream(plainpath, FileMode.Open))
{
    using (FileStream outputstream = new FileStream(copypath, FileMode.CreateNew))
    {
        Object lock1 = new Object();
        long inputlength = inputstream.Length;
        Parallel.For((long)0, (long)(inputlength / bufferSize) + ((inputlength%bufferSize)>0?1:0), (i) =>
        {
            byte[] parallelbuff = new byte[bufferSize];
            long cursor = -1;
            lock (lock1)
            {
                cursor = (long)(i * bufferSize);
                inputstream.Seek(cursor, SeekOrigin.Begin);
                read = inputstream.Read(parallelbuff, 0, buff.Length);
            }
            if (read > 0)
            {
                lock (lock1)
                {
                    outputstream.Seek(cursor, SeekOrigin.Begin);
                    outputstream.Write(parallelbuff, 0, read);
                }
            }
        });
    }
}

这是我的.NET 4.5 C#代码,用于从< plainpath'中复制文件。到' copypath'。

但它不会复制原始文件的某些部分。

你能告诉我我的错误吗?

0 个答案:

没有答案