猿问

使用抽象类的任务启动/停止处理

我有这个代码逻辑来处理我的任务:


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不访问继承类的最少访问的情况下完成任务?


繁星点点滴滴
浏览 108回答 2
2回答

慕尼黑的夜晚无繁华

您可以重写您的抽象类以具有可以知道您的工作何时完成的内部启动方法。假设您的工作是同步的并且不带参数:public abstract class BotTask{&nbsp; &nbsp; private bool Running { get; set; }&nbsp; &nbsp; public CancellationToken Token => _tokenSource.Token;&nbsp; &nbsp; private CancellationTokenSource _tokenSource;&nbsp; &nbsp; public abstract void Start();&nbsp; &nbsp; protected void InternalStart(Action job)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _tokenSource = new CancellationTokenSource();&nbsp; &nbsp; &nbsp; &nbsp; Running = true;&nbsp; &nbsp; &nbsp; &nbsp; job();&nbsp; &nbsp; &nbsp; &nbsp; Running = false;&nbsp; &nbsp; }}public class CustomTask : BotTask{&nbsp; &nbsp; public override void Start()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; InternalStart(MyJob);&nbsp; &nbsp; }}

慕莱坞森

使运行集受保护而不是私有。这样它就不能从外部访问,但它可以被继承自 BotTask 的实体访问
随时随地看视频慕课网APP
我要回答