2017-08-01 108 views
1

我的winforms應用程序正在從SQL Server接收文件,並且我想顯示已經以進度條的形式下載了多少文件。如何跟蹤從SQL Server下載文件的進度?

要恢復的文件,我調用存儲過程和結果保存到一個字節數組:

Dim file() as Byte = SQLCommand.ExecuteScalar() 

這工作得很好,併爲更小的文件,我並不真的需要一個進度條他們完成得如此之快。但是,有些文件可能會變得很大,有些連接可能不太好,所以我真的認爲我需要某種進度指示。

據我所知,我可能需要使用後臺工作線程,我明白如何做到這一點。但是,怎樣才能定期檢查文件已被接收到多少,就像我這樣做,它似乎在一個大塊中執行該操作?

可以這樣做嗎?或者我需要檢查我是如何完全接收文件的?

我的應用程序是VB.Net,但C#答案完全可以接受。

+0

由於你的編程語言是VB.NET,你認爲這個問題及其答案可以幫助你解決這個問題嗎?我不認爲這個問題是重複的,我只是不太瞭解這個過程來發佈一個答案。 https://stackoverflow.com/questions/16688990/how-to-display-progress-bar-while-executing-big-sqlcommand-vb-net –

+1

檢出https://docs.microsoft.com/en-us/ dotnet/framework/data/adonet/sqlclient-streaming-support和https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader.getstream?view=netframework-4.7 –

+1

@KanstantsinArlouski感謝您的建議。其實我剛纔在你評論之前就讀過了。不幸的是,它沒有什麼幫助,因爲在那個問題上,它們處理的是大量的行,而不是一個單一的大BLOB數據。 – Gravitate

回答

3

SqlClient Streaming Support。你需要做的幾個步驟:

鏈接的文章顯示了關於如何完成流式部分的更多細節,在此之後添加進度條並不重要。

+0

謝謝。顯然,我有很多閱讀需要做異步/等待。我對BackgroundWorker更加熟悉,所以對我來說有些新意。我仍然沒有完全理解它,但我認爲這足以讓我有所作爲。 – Gravitate

+0

@Gravitate你應該不需要添加異步/等待等式。同步API應該也可以。但是,如果您在流程中加快異步/等待速度,並且使用它,盡一切辦法,去做就好多了。 –

2

您可以將.NET 4.5中的流式傳輸功能與異步編程模型結合使用。

private static async Task CopyBinaryValueToFile() { 
     string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "binarydata.bin"); 

     using (SqlConnection connection = new SqlConnection(connectionString)) { 
      await connection.OpenAsync(); 
      using (SqlCommand command = new SqlCommand("SELECT [bindata] FROM [Streams] WHERE [id][email protected]", connection)) { 
       command.Parameters.AddWithValue("id", 1); 

       // The reader needs to be executed with the SequentialAccess behavior to enable network streaming 
       // Otherwise ReadAsync will buffer the entire BLOB into memory which can cause scalability issues or even OutOfMemoryExceptions 
       using (SqlDataReader reader = await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess)) { 
        if (await reader.ReadAsync()) { 
        if (!(await reader.IsDBNullAsync(0))) { 
         using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { 
          using (Stream data = reader.GetStream(0)) { 

           // Asynchronously copy the stream from the server to the file we just created 
           await data.CopyToAsync(file); 
          } 
         } 
        } 
        } 
       } 
      } 
     } 
     } 

看到這一點: sqlclient-streaming-support

+0

謝謝,但這是如何讓我跟蹤進度? – Gravitate