【问题标题】:background worker thread后台工作线程
【发布时间】:2011-04-14 13:33:07
【问题描述】:

我正在尝试找出让我的应用程序保持响应的最佳方法。下面显示了我目前正在使用的代码。我发现后台工作线程是要走的路。

    private void cleanFiles()
    {
            if (listView1.CheckedItems.Count != 0)
            {

                // If so, loop through all checked files and delete.

                foreach (ListViewItem item in listView1.CheckedItems)
                {

                    string fileName = item.Text;
                    string filePath = Path.Combine(tFile + fileName);

                    try
                    {

                        File.Delete(filePath);
                    }
                    catch (Exception)
                    {
                        //ignore files being in use
                    }

                    MessageBox.Show("Files Cleaned");
                }


            }
            else
            {
                 MessageBox.Show("Please put a check by the files you want to delete");
            }

        }


    }

    }

【问题讨论】:

    标签: c# winforms multithreading c#-4.0


    【解决方案1】:

    保持程序响应的最简单方法是使用BackgroundWorker

    List<string listWithFilenames = new List<string>();
    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
    bw.RunWorkerAsync(listWithFilenames);
    

    请参阅documentation

    【讨论】:

      【解决方案2】:
      【解决方案3】:

      假设您发布的方法在 UI 线程的上下文中运行, 您需要做的就是包装逻辑(foreach 部分) 在这样的方法中:

      private void DeleteFiles(object state)
      {
      /// your logic here
      }
      

      并致电ThreadPool.QueueWorkItem(new WaitCallback(DeleteFiles)); 来自 cleanfiles 方法。

      如果你运行 .NET 4.0,你可以使用类似的东西:

      Task myTask = Task.Factory.StartNew( () =&gt; DoWork(null)); 然后检查 myTask 的状态,看看它是否完成。

      【讨论】:

      • 我收到错误委托“System.Action”不接受 1 个参数
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-05
      • 2011-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多