我有这个代码逻辑来处理我的任务:public abstract class BaseJob{ public bool Running { get; private set; } public CancellationToken Token => _tokenSource.Token; private CancellationTokenSource _tokenSource; public virtual void Start() { _tokenSource = new CancellationTokenSource(); Running = true; }}现在当我继承时,BaseJob我会遇到这种情况:public class CustomJob: BaseJob{public MyEnum Status {get; private set;}public StopRequested { get; set;}public override async void Start(){ base.Start(); while(!StopRequested){ await MyLongRunningMethod(); } //base.Running = true but I can't access it here!}public async Task<bool> MyLongRunningMethod(){ await Task.Run(()=>{ //more work },this.Token); //someWork return false;}}如您所见,我无法在完成后Running立即将其设置为 false myJob,我想BaseJob处理它。我必须对基类进行哪些代码逻辑更改才能自动检测何时myJob完成,然后在Running = false不访问继承类的最少访问的情况下完成任务?
2 回答
慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
您可以重写您的抽象类以具有可以知道您的工作何时完成的内部启动方法。假设您的工作是同步的并且不带参数:
public abstract class BotTask
{
private bool Running { get; set; }
public CancellationToken Token => _tokenSource.Token;
private CancellationTokenSource _tokenSource;
public abstract void Start();
protected void InternalStart(Action job)
{
_tokenSource = new CancellationTokenSource();
Running = true;
job();
Running = false;
}
}
public class CustomTask : BotTask
{
public override void Start()
{
InternalStart(MyJob);
}
}
- 2 回答
- 0 关注
- 106 浏览
添加回答
举报
0/150
提交
取消