c# - BeginInvoke 问题(委托(delegate)不执行任何操作)

标签 c# invoke begininvoke

希望你一切都好。

我正面临一个关于 BeginInvoke 的奇怪问题,我真的非常需要你的帮助!

我有一个 Reporting 类,其中包含 Report 类型的多个实例

Class Reporting : UserControl
{
  //Reports are inherited from UserControl
  Report _report1;
  Report _report2;
  Report _report3;

  //Instanciate and return the Report corresponding to the passed ID (The report is 
  //instanciated and created only if it's null)   
  public Report GetReport(int reportId);

  public delegate void GenerateReportAsImageDelegate(int reportId,string path)

  //Generate the report and save it as image
  public void GenerateReportAsImage(int reportId,string path)
  {
    if(InvokeRequired)
    {
      BeginInvoke(new GenerateReportAsImageDelegate(GenerateReportAsImage),new      object[]{reportId,path});

    }
    else
    {
      //... Generating the report etc..
    }
 }

  ....
}

它是一个以表单形式显示的用户控件,Windows 服务也使用这个相同的用户控件每分钟生成一次报告(并保存为图像)。

为了每分钟生成一份报告,我使用了 System.Threading.Timer。

这是我的类在服务中生成报告的样子:

class ReportServiceClass
{

  Reporting _reportingObject;
  System.Threading.Timer _timer;

  Public ReportingServiceClass(int reportId)
  {
     _timer = new Timer(new TimerCallback(this.CreateReport), reportId, 0, 1000) 
  }

  private void CreateReport(Object stateInfo)
  {  
     int reportId = Convert.ToInt32(stateInfo);

    //To ensure that the _reportingObject is created on the same thread as the report
    if(_reportingObject == null)
      _reportingObject = new _reportingObject();

    _reportingObject.GenerateReportAsImage(reportId,@"c:\reports\report.PNG")
  }

几乎一切都运行良好.. 除了有时 CreateReport 在 ThreadPool 的另一个线程中执行。因此,当我对报告及其组件(已在另一个线程中创建)执行某些操作时,InvokeRequired 设置为 true,这很明显......但是 BeginInvoke 不执行任何操作!这几乎就像创建报告的线程不再存在......

你们对如何避免这个问题有什么想法吗?

我已经遇到这个问题一个星期了,我用 google 和 stackoverflowed 进行了搜索。但什么都没有!

非常感谢!

最佳答案

我认为你使用了错误的 Invoke,试试这个:

if(this.InvokeRequired)
{
   this.Invoke(new Action<int,string>(GenerateReportAsImage), reportId, path);    
}
else
  ...

关于c# - BeginInvoke 问题(委托(delegate)不执行任何操作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2119416/

相关文章:

c# - 将自定义类的集合绑定(bind)到 TreeView

java - 我调用正确了吗?

.net - 与从非 GUI 线程显示 MessageBox 相关的问题

c# - 等到委托(delegate)被调用

c# - BeginInvoke 的性能影响

c# - 分析 ASP.NET Web 服务的使用

c# - 每次使用 OleDbDataReader 时都需要关闭它吗?

c# - x64 位 Azure 机器上 DateTimeOffset 的平均大小是多少?

c# - Delegate.EndInvoke 究竟做了什么?有必要打电话吗?

java - 如果调用的方法采用可变数量的参数,如何使用 Invoke()