下载文件时,Silverlight无响应

时间:2015-02-26 20:42:25

标签: c# silverlight

我尝试使用以下代码段来通过Silverlight中的SaveFileDialog下载文件:

    public void SaveMediaLocal(string fileName)
    {
        FileInfo fInfo = new FileInfo(fileName);
        if (fInfo.Exists)
        {
            if (fInfo.Length > 0)
            {
                string extension = fInfo.Extension;
                SaveFileDialog dialog = new SaveFileDialog()
                {
                    DefaultExt = extension,
                    Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, fInfo.Extension),
                    FilterIndex = 1,
                    DefaultFileName = fInfo.Name
                };
                if (dialog.ShowDialog() == true)
                {                       
                    try
                    {
                        bool cancelFlag = false;
                        byte[] buffer = new byte[1024 * 1024]; // 1GB buffer
                        using (FileStream dest = (FileStream)dialog.OpenFile())
                        {
                            using (FileStream source = new FileStream(fInfo.FullName, FileMode.Open, FileAccess.Read))
                            {
                                long fileLength = source.Length;
                                long totalBytes = 0;
                                int currentBlockSize = 0;

                                while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    totalBytes += currentBlockSize;
                                    double percentage = (double)totalBytes * 100.0 / fileLength;

                                    dest.Write(buffer, 0, currentBlockSize);
                                }
                            }
                        }
                    }
                    catch
                    {

                    }                        
                }
            }
            else
            {
                //no results
            }
        }
    }

当我使用此代码段时; Silverlight冻结,直到下载完成。 当我使用此代码段时,UI会响应,但不会对较大的文件起作用。

                        using (Stream stream = dialog.OpenFile())
                    {

                        Byte[] bytes = File.ReadAllBytes(fileName);
                        stream.Write(bytes, 0, bytes.Length);
                    }

我有什么东西在这里失踪吗?

1 个答案:

答案 0 :(得分:1)

不要在GUI线程上执行操作。这就是它没有反应的原因。创建新线程或异步进程并在后台中执行操作。