2014-06-06 45 views
0

考慮以下幾點:在Windows中,長異步操作和頻繁的事件處理8.1應用

void event_handler(object sender, ...){ 
    DoSomething(); 
    } 

    void DoSomething(){ 
    // change some page's state 
    // change some page's private members 
    var someData = await LongOperation(); 
    // change some page's state 
    // change some page's private members 
    } 

現在,我想以下行爲:當以前LongOperation()尚未完成,如果event_handler被觸發但是,這樣一個LongOperation()必須被取消。

什麼是最簡單的和首選的方法來做到這一點?

回答

3

取消通過CancellationToken最好的處理:

private CancellationTokenSource _cts; 
async void event_handler() 
{ 
    if (_cts != null) 
    _cts.Cancel(); 
    _cts = new CancellationTokenSource(); 
    await DoSomethingAsync(); 
} 

async Task DoSomethingAsync() 
{ 
    // change some page's state 
    // change some page's private members 
    var someData = await LongOperationAsync(_cts.Token); 
    // change some page's state 
    // change some page's private members 
} 

有各種優化,也就是重新使用以前CancellationTokenSource如果前面的操作不是取消等,但這些代碼說明了一般原理。