簡體   English   中英

如何在wp7中使用多線程?

[英]How to use multithreading in wp7?

我正在開發wp7應用程序。 我需要將一些文件從服務器下載到手機上。 從列表框中選擇文件。 嘗試下載單個項目時,下載效果很好。 但是,當我嘗試同時下載多個項目時,出現錯誤。 如何同時下載多個項目?

這是我下載文件的代碼。

IList<Item> selectedItems = documents.Where( p => p.IsChecked == true ).ToList();
foreach ( var item in selectedItems )
{
   FileDownload objDownload = new FileDownload();

   objDownload.FileName = item.Title;
   objDownload.Url = item.Link;
   objDownload.DocId = item.DocId;

   ThreadPool.QueueUserWorkItem( t =>
   {
     Dispatcher.BeginInvoke( () =>
     {
       objDownload.DownloadFile();
     } );
     Thread.Sleep( 0 );
   } );
}

這是FileDownload類中的DownloadFile()方法

public void DownloadFile()
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create( Url );
    request.AllowReadStreamBuffering = false;
    request.BeginGetResponse( new AsyncCallback( DownloadFileData ), request );
}

private void DownloadFileData( IAsyncResult result )
{
    try
    {
        AddToDownloadList();
        IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
        string fileName = "DownloadedFiles\\" + FileName;
        if ( !isf.DirectoryExists( "DownloadedFiles" ) )
            isf.CreateDirectory( "DownloadedFiles" );

        if ( !isf.FileExists( fileName ) )
        {
            IsolatedStorageFileStream streamToWriteTo = new IsolatedStorageFileStream( fileName, FileMode.Create, isf);
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse( result );
            Stream str = response.GetResponseStream();
            byte [ ] data = new byte [ 16 * 1024 ];
            int read;
            long totalValue = response.ContentLength;
            while ( ( read = str.Read( data, 0, data.Length ) ) > 0 )
            {
                streamToWriteTo.Write( data, 0, read );
            }
            string file = streamToWriteTo.ToString();
            streamToWriteTo.Close();
        }
        OfflineStatus = true;
    }
    catch ( Exception ex )
    {
        OfflineStatus = false;
    }
}

如何使用多線程下載文件。

您的代碼有一些問題:

  • 您必須關閉/處置商店。 最好的做法是使用using語句

    使用(var store = IsolatedStorageFile.GetUserStoreForApplication()){//任務}

  • 使用多個線程下載東西不會獲得任何性能*-連接是瓶頸,而不是每秒的CPU周期。

  • 如果您有一個多線程應用程序,對於(.isf.DirectoryExists(“ DownloadedFiles”))無法在相同位置執行IO,則很簡單。 您有比賽條件。 如果一個線程開始創建目錄,而第二個線程在第一個完成之前檢查目錄,該怎么辦?

  • 不要用catch吞下異常(Exception ex)。 異常經常包含有關問題的信息。

我會使用類似的解決方案來解決這個問題, 這一個

*多線程應用程序往往不確定,下載速度可能會更快,但是在這種情況下,最有可能的是下載速度會更慢。

您正在循環中覆蓋objDownload對象,從而破壞了先前的引用。 創建FileDownload列表並添加每個以保持獨立。

rob對於您的objDownload是正確的,但由於WebRequest.BeginGetResponse是異步且非阻塞的,因此完全不需要使用ThreadPool.QueueUserWorkItem + Dispatcher.BeginInvoke 您當前的代碼移至后台線程,然后移至UI線程,然后執行異步HTTP操作,該操作在后台線程上返回(這很瘋狂)。

旁注:您正在下載的文件是否很大(例如> 1mb)? 如果是這樣,您應該使用后台文件傳輸 -即使您的應用程序未運行,它們也會繼續下載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM