C#:多线程下载

时间:2014-12-15 04:23:09

标签: c# multithreading

基本上,我有两个主线程。一个负责下载数据。另一个负责将数据插入sqlite数据库。插入线程一直插入,直到找到下载完成它的工作。

我的问题是,如何判断下载完成?我知道我可以使用Task.IsCompleted来获取信号。但是在下载线程中有点复杂。我使用了foreach-block,并且在每个循环中都有一个新的子线程打开。我使用一个新任务来包含整个foreach-block并尝试获取新任务的Task.IsCompleted,但是当Task.IsCompleted为true时,子线程没有完成,它们仍在运行。那么当所有下载线程结束时我应该如何知道呢?然后我可以跳出while-true块。

private Task BeginDownload(PackageCategory type)
{
    if (IsMagazineSelected)
    {
       ObservableCollection<Category_Info> categorylist = new ObservableCollection<Category_Info>() { };
       foreach (var category in MagazineCategoryList)
       {
          if (category.IsChecked && category.IsEnabled)
          {
             categorylist.Add(category);
             _allData.MagazineCount += category.MagazineList.Count;
          }
       }
       _allData.CollectCategoryData(categorylist);

       if (MagazineCategoryTask != null)
       {
           while (true)
           {
              if (MagazineCategoryTask.IsCompleted)
              {

                 DownloadMagazinePartTask = Task.Run(delegate
                 {
                     foreach (var category in categorylist)
                        {
                             category.IsEnabled = false;
                             category.MagazineList.ForEach(x => x.CategoryCode = category.CategoryCode);

                              _allData.CollectMagazineData(category.MagazineList);

                              if (!category.TotalCount.Equals("0"))
                              {
                                    DownloadMagazinePartTask1 = Task.Run(async delegate
                                    {
                                        LogHelper.LogInfo(string.Format("*************Begin to download the Latest magazines; Category id: {0}, name {1}.", category.CategoryCode, category.CategoryName));

                                        await DownloadMagazineTask(type, category.MagazineList).ContinueWith(anc =>
                                        {
                                            DownloadMagazinePartTask = Task.Run(delegate
                                            {
                                            LogHelper.LogInfo(string.Format("*************Begin to download History magazines; Category id: {0}, name {1}.", category.CategoryCode, category.CategoryName));

                                            foreach (var magazine in category.MagazineList)
                                            {
                                                MagazineService.GetHistoryMagazineByMagazineGuid(magazine.MagazineGUID).ContinueWith(async ancc =>
                                                {
                                                    List<Magazine_Info> historyMagazines = GetMagazineListFromResult(ancc.Result);
                                                    historyMagazines.RemoveAt(0);
                                                    historyMagazines.ForEach(x =>
                                                    {
                                                        x.MagazineGUID = magazine.MagazineGUID;
                                                        x.CategoryCode = magazine.CategoryCode;
                                                        x.CodeName = magazine.CodeName;
                                                        x.IconList = magazine.IconList;
                                                    });

                                                    _allData.CollectMagazineData(historyMagazines);
                                                    _allData.MagazineCount += historyMagazines.Count;
                                                    LogHelper.LogInfo(string.Format("Download {0} history magazines! Magazine name is {1}, Guid is {2}", historyMagazines.Count, magazine.MagazineName, magazine.MagazineGUID));

                                                    await DownloadMagazineTask(type, historyMagazines, true);
                                                });

                                            }

                                        });

                                    });
                                    });
                                }
                            }
                        });
                        break;
                    }
                }
            }
        }




        Task.Run(delegate 
        {
            int times = 0;
            while (true)
            {
                if (_allData.MagazineList != null && _allData.MagazineList.Count != 0) 
                { 
                    int rownum = MagazineService.InsertMagazines(_allData.MagazineList);
                    LogHelper.LogInfo(String.Format("Times: {0}: Insert Magazines: {1} in total {2}", times.ToString(), _allData.MagazineList.Count, rownum));
                }
                if (_allData.CatalogList != null && _allData.CatalogList.Count != 0) 
                {
                    bool insertResult = CatalogService.InsertCatalogs(_allData.CatalogList);
                    LogHelper.LogInfo(String.Format("Times: {0}: Insert Catalogs: {1}", times.ToString(), _allData.CatalogList.Count.ToString()));
                }
                if (_allData.MagazineArticleList != null && _allData.MagazineArticleList.Count != 0) 
                { 
                    bool insertArticleResult = MagazineArticleService.InsertArticles(_allData.MagazineArticleList);
                    LogHelper.LogInfo(String.Format("Times: {0}: Insert Articles: {1}", times.ToString(), _allData.MagazineArticleList.Count.ToString()));
                }

                if (_allData.MagazineList != null && _allData.CatalogList != null && _allData.MagazineArticleList != null)
                {
                    DownloadMagazinePartTask.Wait();
                    if (DownloadMagazinePartTask.IsCompleted && DownloadMagazinePartTask1.IsCompleted) //If the downloading thread is completed, I need to jump out here 
                    {
                        MagazineService.InsertMagazines(_allData.MagazineList);
                        CatalogService.InsertCatalogs(_allData.CatalogList);
                        MagazineArticleService.InsertArticles(_allData.MagazineArticleList);
                        LogHelper.LogInfo("All Insert Work is Done! Quit!");
                        break;
                    }
                }

                times++;

            }


        });

        return Task.FromResult<string>(null);
    }

0 个答案:

没有答案