IAsyncResult实例上的FromAsync方法:“不包含'FromAsync'的定义”

时间:2018-08-10 14:57:56

标签: c# .net asynchronous download .net-framework-version

我需要使用允许我在标题上使用“ Range”的类,并同时更新进度条。 我看到一个帖子,有人发布了以下代码,应该可以帮助HttpWebRequest实现进度条:

public static void CopyToStreamAsync(this Stream source, Stream destination, Action<Stream, Stream, Exception> completed, 
                                         Action<uint> progress, uint bufferSize, uint? maximumDownloadSize, TimeSpan? timeout)
    {
        byte[] buffer = new byte[bufferSize];

        Action<Exception> done = exception =>
        {
            if (completed != null)
            {
                completed(source, destination, exception);
            }
        };

        int maxDownloadSize = maximumDownloadSize.HasValue ? (int)maximumDownloadSize.Value : int.MaxValue;
        int bytesDownloaded = 0;
        IAsyncResult asyncResult = source.BeginRead(buffer, 0, new[] { maxDownloadSize, buffer.Length }.Min(), null, null);
        Action<IAsyncResult, bool> endRead = null;
        endRead = (innerAsyncResult, innerIsTimedOut) =>
        {
            try
            {
                int bytesRead = source.EndRead(innerAsyncResult);
                if (innerIsTimedOut) done(new TimeoutException());

                int bytesToWrite = new[] { maxDownloadSize - bytesDownloaded, buffer.Length, bytesRead }.Min();
                destination.Write(buffer, 0, bytesToWrite);
                bytesDownloaded += bytesToWrite;

                if (progress != null && bytesToWrite > 0) progress((uint)bytesDownloaded);

                if (bytesToWrite == bytesRead && bytesToWrite > 0)
                {
                    asyncResult = source.BeginRead(buffer, 0, new[] { maxDownloadSize, buffer.Length }.Min(), null, null);
                    asyncResult.FromAsync((ia, isTimeout) => endRead(ia, isTimeout), timeout);

                }
                else
                {
                    done(null);
                }
            }
            catch (Exception exc)
            {
                done(exc);
            }
        };

        asyncResult.FromAsync((ia, isTimeout) => endRead(ia, isTimeout), timeout);
    }

问题是我什至无法测试,因为“ asyncResult.FromAsync”返回“不包含'FromAsync'的定义且没有扩展方法'FromAsync'的“错误。

有人可以帮助我了解应该使用哪些引用或哪个.NET Framework,以便代码起作用?

谢谢

0 个答案:

没有答案