So, I have a summary on my user interface that in SelectionChanged it goes asynchronously to the web service to discard some information that will be displayed in the user interface (using the new async / await C # 5 keywords). What I want to do is cancel the current asynchronous request before sending a new one; for example, if the user uses the keyboard to quickly cycle through all combobox elements, the SelectionChanged event may fire several times (generating several asynchronous requests) before even the first async request is returned.
So, my asynchronous call function, which is called from the SelectionBlanged combobox event, looks like this:
public async Task<Connections> ConnectionsAsync() { return await Task.Factory.StartNew(() => Connections, _cancellationTokenSource.Token); }
Where Connections is a property that disconnects and enters the web service. Therefore, since the CancellationTokenSource cannot be reused after cancellation, I think about it:
public async Task<Connections> ConnectionsAsync() { _cancellationTokenSource.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); return await Task.Factory.StartNew(() => Connections, _cancellationTokenSource.Token); }
The problem is that sometimes I call Cancel () when there is no async command (for example, the first time this function is called); therefore, if I hook up cancel event handlers, they will be called, even before I make an asynchronous request.
In any case, check if an asynchronous request is running? Besides me, I am doing something 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 several asynchronous functions that use the same CancellationTokenSource file, so I will have to implement this "plumbing" in all these functions. Is this a better approach? Or is there a better way?
Also, if I published _cancellationTokenSource publicly so that other classes can register delegates with cancellation, what is the best way to βmigrateβ these delegates to a new CancellationTokenSource, since I create a new one each time?
Thanks in advance!