C# Backgroundworker New Issue

本文关键字:Issue New Backgroundworker | 更新日期: 2023-09-27 17:57:26

我正在为我的问题寻找一个有效的解决方案。我正在使用VS 2010。我想从wcf服务方法中进行一系列操作,并将每个操作状态发送回调用客户端。我已经用回调合约设置了wcf,并使用双工信道,我可以连接到wcf。当我开始长时间运行操作时,有时会触发回调,有时不会。我不知道为什么。下面是我所遵循的方法。

在wcf服务方法中,

 public void Start()
  {
      List<Employee> empLists = GetEmpData();  // geting lots of employee objects
      foreach(Employee emp in empLists)        // maybe 1000 records
      {
          StartlongRunning(emp);
      }
  }
 private void StartlongRunning(Employee emp)
 {
     // here i am creating a new background worker...
     // Here i am registering for RunWorkerCompleted, DoWork, ReportProgress events...
     bgw.RunWorkerAsync(emp)
 }
 void bgw_DoWork(object sender, DoWorkEventArgs e)
 {
     Employee emp = (Employee)e.Argument;
     using (ClassA p = new ClassA(emp.ID)) // this class is from another dll.
     {
       e.Result = p.StartProcess(emp.Code);
     } 
 }
 void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
    // This is not calling properly.
    // Sometimes this method is working...most of the time it is not working..
    // here i am unregistering the registerd DoWork, RunWorkerCompleted events...
    // calling bgw.Dispose(); // i tried without this also;...but no use...
    // from here I am firing the callback to client...
 }

以下是StartProcess方法的实现。

 public string StartProcess(string empcode)
 {
     // call to another method1() // here saving to DB frequently. works fine
     // call to another method2() // here also saving to DB frequently. works fine
     // call to someother method3()  // here also some DB insert frequently. fine
     // call to Method4() // here also some DB insert.
                          // this method is not calling frequently..
                          // sometimes it is calling but most of times not..why ???
     return value;
 }
 private void SaveToDB(args1, args2...)
 {
     DatabaseHelper.Save(args1, args2.....); // this static class is from another dll
     // only DB operation in this static class..
 }

这个静态类的实现如下所示。

using (SqlConnection conn = new SqlConnection(DBConnection))
{
     conn.open;
      using (SqlCommand cmd = conn.CreateCommand())
      {
         ...adding parameters
         cmd.ExecuteNonQuery();
      }
      conn.close();
}

如果StartProcess返回,那么后台工作程序将执行RunWorker方法。但这并没有发生。这里怎么了?

我正在为每个后台工作人员创建每个ClassA对象。一旦ClassA的一个对象完成,它就会被处理掉。

但我不知道为什么StartProcess没有正确地返回呼叫。

在我的实现中,后台工作者之间是否存在ClassA对象的重叠??

C# Backgroundworker New Issue

我认为问题在于您在循环中调用RunWorkerSync时没有检查它是否繁忙。您应该使用列表作为参数来调用RunWorkerSync,而不是尝试在不同的线程中启动所有工作。

我会这样做:

 public void Start()
 {
     List<Employee> empLists = GetEmpData();  // geting lots of employee objects
     StartlongRunning(empLists);
 }

并相应地更改bgw_DoWork。

如果您需要查看进度,可以为每个员工对象调用ReportProgress。

如果您想创建一个同时与几个backgroundWorker一起工作的应用程序,您应该为正在执行的每个操作初始化新的backgroundWorkers对象。。这将解决问题。