2017-03-15 59 views
0

因此,我有一個方法可以在datagridview上執行調用,並且對於運行它的第一個線程可以正常工作,但是當第二個線程嘗試使用該方法時,下載部分仍然功能,但是調用語句中止時的第一線工作,並開始改變這兩個我無法在多個線程上調用SQL命令C#

public void ByteTransferResume(int indexResume) 
{ 
    HttpWebRequest req; 
    HttpWebResponse resp; 
    req = (HttpWebRequest)HttpWebRequest.Create(FileLocationName); 
    req.AddRange((int)fileInfoDestination.Length); 
    resp = (HttpWebResponse)(req.GetResponse()); 
    long fileLength = resp.ContentLength; 
    FileLocationLength = fileLength; 
    using (Stream responseStream = resp.GetResponseStream()) 
    { 
     int iBufferSize = 1024; 
     iBufferSize *= 1000; 
     using (FileStream saveFileStream = new FileStream(FileDestination, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) 
     { 
      int iByteSize; 
      byte[] downBuffer = new byte[iBufferSize]; 

      while ((iByteSize = responseStream.Read(downBuffer, 0, downBuffer.Length)) > 0) 
      { 
       saveFileStream.Write(downBuffer, 0, iByteSize); 

       FileInfo fileInfoDestinations = new FileInfo(FileDestination); 

       FileDestinationLength = (int)fileInfoDestinations.Length; 

       double downloadProgress = ((double)FileDestinationLength/FileLocationLength) * 100; 

       // MessageBox.Show(downloadProgress.ToString()); 

       dgvDownloadInfo.Invoke(new dgvCommandDelegate(DGVCommand), new object[] { $"UPDATE Download_Info SET [Progress] = '{downloadProgress:F2}%' WHERE [File Name] = '{thread1[indexResume].Name}'" }); 

       //MessageBox.Show(thread1[indexResume].Name); 
       //MessageBox.Show(indexResume.ToString()); 
       // dgvDownloadInfo.Invoke(new dgvConnectionDelegate(DGVConnection)); 
       Thread.Sleep(10); 
      } 
     } 
    } 
} 
+0

你嘗試添加鎖()語句? – daniell89

+0

我不熟悉鎖定語句? – foreveraphone

+0

您使用的是什麼RDBMS? –

回答

0

也許這將幫助你:

public object _lock = new object(); 
public void ByteTransferResume(int indexResume) 
{ 
    lock (_lock) 
    { 
     HttpWebRequest req; 
     //rest of your method   
    } 
    } 
+0

它沒有工作我害怕,謝謝無論如何,對不起,這是一個痛苦,即時通訊非常新,但我很感激所有人:)最終生病了! :) – foreveraphone