【问题标题】:Why i'm getting cross thread exception while updating label in backgroundworker progresschanged event?为什么在后台工作进程进度更改事件中更新标签时出现跨线程异常?
【发布时间】:2016-03-24 17:10:20
【问题描述】:

我有一个后台工作人员,我在其中启动了一个新的后台工作人员

DirectoryInfo MySubDirectory;
List<FileInfo> l;
object[] CurrentStatus;

private void _FileProcessingWorker_DoWork(object sender, DoWorkEventArgs e)
{
    int countmore = 0;
    try
    {
        DirectoryInfo[] MySubDirectories = (DirectoryInfo[])e.Argument;
        for (int i = 0; i < MySubDirectories.GetLength(0); i++)
        {
            MySubDirectory = MySubDirectories[i];

            l = new List<FileInfo>();
            if (_FileCountingWorker.IsBusy == false)
                _FileCountingWorker.RunWorkerAsync();

            CurrentStatus = new object[6];
            int totalFiles = l.Count;
            CurrentStatus[3] = i.ToString();
            countmore += totalFiles;
            CurrentStatus[4] = countmore;
            _FileProcessingWorker.ReportProgress(0, CurrentStatus);

            string CurrentDirectory = "Current Directory: " + MySubDirectory.Name;

            foreach (FileInfo MyFile in l)
            {
                CurrentStatus = new object[6];
                if (_FileProcessingWorker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                 }

                 if (MyFile.Extension.ToLower() == ".cs" || MyFile.Extension.ToLower() == ".vb")
                 {
                     string CurrentFile = "Current File: " + MyFile.Name;
                     string CurrentFileWithPath = MyFile.FullName;

                     CurrentStatus[0] = CurrentDirectory;
                     CurrentStatus[1] = CurrentFile;
                     _FileProcessingWorker.ReportProgress(0, CurrentStatus);

                     List<string> Result = SearchInFile(CurrentFileWithPath, "if");

                     if (Result != null && Result.Count > 0)
                     {
                         CurrentStatus[2] = Result;
                         _FileProcessingWorker.ReportProgress(0, CurrentStatus);
                      }
                  }
              }
          }
      }
      catch (Exception err)
      {
          return;
      }
  }

我正在检查其他后台工作人员是否不忙,如果不启动它

if (_FileCountingWorker.IsBusy == false)
    _FileCountingWorker.RunWorkerAsync();

在新的backgroundworker dowork事件中

private void _FileCountingWorker_DoWork(object sender, DoWorkEventArgs e)
{
    CountFiles(MySubDirectory, l);
}

在计数文件中

int countingFiles = 0;
private void CountFiles(DirectoryInfo di, List<FileInfo> l)
{
    try
    {
        l.AddRange(di.EnumerateFiles());
    }
    catch
    {
        string fff = "";
    }

    try
    {
        if (di.FullName != BasePath)
        {
            IEnumerable<DirectoryInfo> subDirs = di.EnumerateDirectories();
            if (subDirs.Count() > 0)
            {
                foreach (DirectoryInfo dir in subDirs)
                {
                    CountFiles(dir, l);
                    countingFiles += 1;
                    if (countingFiles == 8382)
                    {
                        string hhhhh = "";
                    }
                    CurrentStatus[5] = countingFiles;
                    _FileCountingWorker.ReportProgress(0,CurrentStatus);
                }
            }
        }
    }
    catch 
    {
        string yyy = "";
    }
}

然后在第二个后台worker进度改变

private void _FileCountingWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    if (typeof(object[]) == e.UserState.GetType())
    {
        object[] StatusMsg = (object[])e.UserState;
        if (6 == StatusMsg.GetLength(0))
        {
            if (StatusMsg[5] != null)
            {
                lblCountingFiles.Text = StatusMsg[5].ToString();
            }
        }
    }
}

异常上线:

lblCountingFiles.Text = StatusMsg[5].ToString();

跨线程操作无效:控件“lblCountingFiles”从创建它的线程以外的线程访问

我正在更新ProgressChanged 事件中的标签。为什么会出现异常?
又该如何解决呢?

【问题讨论】:

  • 有趣。我只是尝试了一个小例子(从第一个的DoWork 开始第二个后台工作人员,报告进度等),它工作正常(检查CheckForIllegalCrossThreadCalls 是真的)。希望有人可以帮助你。
  • 您无法从子线程更新 UI 线程。您需要使用委托或某些线程安全的方法来更新内容,例如将消息发回 UI。并允许它基于线程安全的 Timer 对象更新 ITSELF,从其子线程中标记和处理其帖子消息队列。
  • 查看此问题以获取更多信息:stackoverflow.com/questions/13438948/…

标签: c# .net winforms


【解决方案1】:

您正在从另一个BackgroundWorker 线程调用DoWork 中的_FileCountingWorker.RunWorkerAsync();。 因此,当_FileCountingWorker 报告进度时,它不会返回到 UI 线程,因为它不是从 UI 线程启动的。这就是为什么你得到跨线程异常。

尝试从 UI 线程或 _FileProcessingWorker_ProgressChanged 事件调用 _FileCountingWorker.RunWorkerAsync()。

否则你可以使用:

private void _FileCountingWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    if (!Dispatcher.CheckAccess()) // CheckAccess returns true if you're on the dispatcher thread
    {
        Dispatcher.Invoke(new Action<object, ProgressChangedEventArgs>(_FileCountingWorker_ProgressChanged), sender, e);
        return;
    }
    if (typeof(object[]) == e.UserState.GetType())
    {
        object[] StatusMsg = (object[])e.UserState;
        if (6 == StatusMsg.GetLength(0))
        {
            if (StatusMsg[5] != null)
            {
                lblCountingFiles.Text = StatusMsg[5].ToString();
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    我认为问题出在你的主线程上

    object[] CurrentStatus;
    

    在后台你可以在报告进度到达之前更新它 (或同时)

    杀死上面
    只需在 do_work 中创建对象

    object[] CurrentStatus = new object[6];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      • 2015-04-18
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      相关资源
      最近更新 更多