BackgroundWorker意外死亡 [英] BackgroundWorker dies unexpectedly

查看:98
本文介绍了BackgroundWorker意外死亡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public Mainform()
{
...
        // scheduler
        scheduler.DoWork += new System.ComponentModel.DoWorkEventHandler(scheduler_DoWork);
        scheduler.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(scheduler_RunWorkerCompleted);
        scheduler.WorkerReportsProgress = false;
        scheduler.WorkerSupportsCancellation = true;
...

...

    scheduler_DoWork(this, null);
    scheduler.RunWorkerAsync(1000);

...
}    

void scheduler_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            scheduler_Enabled = false;
            CustomExceptionHandler eh = new CustomExceptionHandler();
            eh.HandleUnhandledException(e.Error, "scheduler");
        }
        if(scheduler_Enabled)  
        {
            scheduler.RunWorkerAsync(1000);
        }
    }


void scheduler_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{

 try
 {            
    try
    {
      ...do some stuff
    }
    catch(MyException ex)
    {
       ThreadSafeShowError();
    }
    finally
    {}
    ...do more stuff
 }
 finally
 {
   if (e != null && e.Argument != null)
   {
    Thread.Sleep((int)e.Argument);
   }
 }
}

backgroundworker线程意外死亡,没有引发任何异常.我在开发过程中没有遇到这个问题,似乎很难重现.我怀疑在scheduler_DoWork中工作时可能发生了跨线程异常.我尝试显式更新UI,而不检查是否InvokeRequired,并且线程继续运行,而发行版本中没有问题.怎么会这样? (应该发生跨线程异常)如何确定导致线程死亡的原因?关于如何找出问题出在哪里或如何调试此问题的任何建议将受到赞赏?

The backgroundworker thread died unexpectedly without any exception being thrown. I did not encounter this problem during development and it seems to be hard to reproduce. I suspected that maybe a cross thread exception was occurring when I am doing work in the scheduler_DoWork. I have tried to explicitly update the UI without checking if InvokeRequired and the thread continues to run without problems in a release build. How can this be? (Cross thread exception should occur) How can I determine what causes the thread to die? Any suggestions on how to figure out what is going wrong or how to debug this issue will be appreciated?

推荐答案

UI线程上可能不会触发RunWorkerCompleted事件.如果不是,线程将结束并且您的调度程序对象将被垃圾回收,这将使其看起来像是退出而没有错误.请参阅发布更多详细信息. 此处

The RunWorkerCompleted event might not be fired on the UI Thread. If it is not, then the thread will end and your scheduler object will be garbage collected, which will make it seem like it just quit with no error. See this post for more details. Here and here are SO posts about this.

这篇关于BackgroundWorker意外死亡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆