Correctly cancel async operation and fire it again

后端 未结 3 766
走了就别回头了
走了就别回头了 2020-12-18 11:37

How to handle case, where user might hit the button, which invokes long running async operation, multiple time.

My idea was first check if the async operation is run

3条回答
  •  春和景丽
    2020-12-18 12:28

    Why not follow the BackgroundWorker pattern and break out of the loop in DrawContent?

    private bool _cancelation_pennding=false;
    private delegate DrawContentHandler(TimePeriod period, Token token)
    private DrawContentHandler _dc_handler=null;
    
    .ctor(){
        this._dc_handler=new DrawContentHandler(this.DrawContent)
    }
    public void CancelAsync(){
        this._cancelation_pennding=true;
    }
    public void Draw(){
        this._dc_handler.BeginInvoke(this.TimePeriod, this.cts.Token)
    }
    private void DrawContent(TimePeriod period, Token token){
        loop(){
            if(this._cancelation_pennding)
            {
                break;
            }
    
            //DrawContent code here
        }
        this._cancelation_pennding=false;
    }
    

提交回复
热议问题