C# 如何以Fire和Forget的形式调用委托调用
我有一个.NET标准库,可以报告其进度。我希望在进度报告方法完成之前,不要阻止程序。取而代之的是,我想要一个火与忘的模式,在这个模式中,工作可以在C# 如何以Fire和Forget的形式调用委托调用,c#,events,delegates,fire-and-forget,C#,Events,Delegates,Fire And Forget,我有一个.NET标准库,可以报告其进度。我希望在进度报告方法完成之前,不要阻止程序。取而代之的是,我想要一个火与忘的模式,在这个模式中,工作可以在DoWork()内继续进行 用线程 class Foo { public delegate void ProgressEvent(double progress, double max); public ProgressEvent ReportProgress { get; set; } pu
DoWork()内继续进行
用线程
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;
}
}
class-Foo
{
公共委托无效进度事件(双倍进度,双倍最大值);
public ProgressEvent ReportProgress{get;set;}
公共工程
{
线程工作线程=新线程(()=>
{
对于(int i=0;i<1000;i++)
{
//工作
睡眠(1000);
ReportProgress?.Invoke(i,1000);//我不想在这里等待方法返回
}
});
workerThread.Start();
返回;
}
}
试试关键字async
wait
@folmerbrem您是否考虑过使用IProgress
()?@MichaelMao是的,我正在研究异步模式,因为它看起来确实是一种方式。但在使用委托时,我很难将其融入我的上下文中。如果你能抽出一些时间,举个例子会很有帮助。你能举个例子吗?你将如何使用这个class@MichaelMao我添加了一个代码,可能表示客户如何使用库
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();
});
}
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;
}
}