c# - Best practice for consistently cancelling Async CancellationTokenSource -


so have combobox on ui on selectionchanged asynchronously goes off web service pull information displayed on ui (using new c#5 async/await keywords). i'm looking cancel current async request before sending new one; example if user uses keyboard cycle through of combobox items, selectionchanged event fire multiple times (generating multiple async requests) before first async request returns.

so async function gets called combobox's selectionchanged event looks this:

public async task<connections> connectionsasync() { return await task.factory.startnew(() => connections, _cancellationtokensource.token); } 

where connections property goes off , hits web service. because cancellationtokensource cannot reused once cancelled, i'm thinking of doing this:

public async task<connections> connectionsasync() { _cancellationtokensource.cancel(); _cancellationtokensource = new cancellationtokensource(); return await task.factory.startnew(() => connections, _cancellationtokensource.token); } 

the problem though calling cancel() when there no async command running (e.g. first time function called); if hookup cancellation event handlers called, before have made async request.

is there anyway check if async request running? other me doing like:

public async task<connections> connectionsasync() { if (_runningasynccommand) _cancellationtokensource.cancel(); _cancellationtokensource = new cancellationtokensource(); _runningasynccommand = true; return await task.factory.startnew(() => connections, _cancellationtokensource.token); _runningasynccommand = false; } 

i have few async functions use same cancellationtokensource, have implement "plumbing" in of functions. best approach? or there better way?

also, if expose _cancellationtokensource publically other classes can register cancellation delegates it, best way "transfer" these delegates on new cancellationtokensource, since i'm creating new 1 every time?

thanks in advance!

looks match made in heaven reactive extensions. define throttle time has elapse (let's 300ms) when observing events combobox before creating task

code snippet subscribing textbox change events, you'll idea:

var input (from evt in observable.fromevent<eventargs>(txt, "textchanged") select ((textbox)evt.sender).text) .throttle(timespan.fromseconds(1)) .distinctuntilchanged(); using (input.subscribe(inp => console.writeline("you wrote: " + inp))) { // stuff } 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -