-1

我有一个能够报告其进度的 .NET Standard 库。我希望程序在进度报告方法完成之前不要阻塞。相反,我想要一个即发即弃的模式,工作可以在里面继续DoWork()

class Foo
{
   public delegate void ProgressEvent(double progress, double max);
   public ProgressEvent ReportProgress { get; set; }

   public void DoSomeWork()
   {
      for(int i = 0; i < 1000; i ++)
      {
         // Do work
         ReportProgress?.Invoke(i, 1000);   // I do not want to wait for the method to return here
      }
   }
}

到目前为止,我已经把分配给 ReportProgress 的方法体作为一个要求,它必须快速执行。但是如果有一个好的编码解决方案,我不想依赖需求。

有可能将 ReportProgress 的调用包装在一个新线程中,但这似乎效率低下 - 这将产生 1000 个线程。

这个问题表明我应该以某种方式在我的类中公开一个 ThreadPool,但我不确定这是否有意义: 在 C# 中执行火灾并忘记方法的最简单方法?

您将如何处理这种情况?

编辑: 我相信班级的用户是这样使用它的。请注意,远程数据库的更新可能很慢。这个客户是我需要重新考虑结构的原因。

void HandleRequest(int requestID)
{
    
    Thread workerThread = new Thread(()=>
    {
        double currentProgress = 0;
        Foo f = new Foo();
        f.ReportProgress = (progress, max) =>
        {
            double newProgress = progress/max;
            if(newProgress > currentProgress)
            {
                currentProgress = newProgress;
                UpdateRemoteDataBase(currentProgress, requestID);
            }
        }
        t.DoWork();
    });
}

4

1 回答 1

0

把你的包裹起来怎么DoSomeworkThread

 class Foo
    {
        public delegate void ProgressEvent(double progress, double max);
        public ProgressEvent ReportProgress { get; set; }

        public void DoSomeWork()
        {
            Thread workerThread = new Thread(() =>
            {
                for (int i = 0; i < 1000; i++)
                {
                    // Do work
                    Thread.Sleep(1000);
                    ReportProgress?.Invoke(i, 1000);   // I do not want to wait for the method to return here
                }
            });
            workerThread.Start();
            return;
        }
    }
于 2020-12-04T03:54:46.743 回答