[英]How to invoke a delegate call as Fire-And-Forget
我有一个能够报告其进度的 .NET 标准库。 我希望程序在进度报告方法完成之前不要阻塞。 相反,我想要一个即发即弃的模式,工作可以在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 个线程。
这个问题表明我应该以某种方式在我的 class 中公开一个 ThreadPool,但我不确定这是否有意义: 在 C# 中执行火灾并忘记方法的最简单方法?
您将如何处理这种情况?
编辑:我相信 class 的用户正在这样使用它。 请注意,远程数据库的更新可能很慢。 这个客户是我需要重新考虑结构的原因。
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();
});
}
用Thread
包装你的DoSomework
怎么样
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.