Reputation: 440
I'm using the Google API with .NET library. I am building a Windows installed app, and want to allow the user to cancel if it is taking too long. Can anyone show me some sample C# code to cancel an Execute() or ExecuteAsync() call? I am running all the API communications in a separate thread. That API thread will check a global variable to see if it should stop, but if that separate thread is stuck on an Execute(), how can I stop it? I'm hoping there is a more elegant way that just calling Abort() on the thread. Here is some pseudo-code:
CancellationTokenSource tokenSource;
CalendarService cs;
private void Form1_Load(object sender, System.EventArgs e)
{
// Create the thread object
m_syncWorker = new SyncWorker();
m_workerThread = new Thread(m_syncWorker.StartSync);
// Create the Cancellation Token Source
tokenSource = new CancellationTokenSource();
// Start the worker thread.
m_workerThread.Start();
// Waits, and monitors thread... If user presses Cancel, want to stop thread
while(m_workerThread.IsAlive)
{
if(bUserPressedCancelButton) tokenSource.Cancel();
}
}
public void StartSync()
{
UserCredential credential;
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
ClientSecret = "yyyyyyyyyyyyyyyyyyyyy"
},
new[] { CalendarService.Scope.Calendar },
"[email protected]",
CancellationToken.None,
new FileDataStore("Somefolder"));
// Create the service
cs = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "My App",
});
// do some stuff...
// wait for this to complete, or user cancel
InsertAllEventsTask(e).Wait();
}
private async Task InsertAllEventsTask(Event e)
{
try
{
// trying to cancel this...
await cs.Events.Insert(e, "primary").ExecuteAsync(tokenSource.Token);
}
catch (TaskCanceledException ex)
{
// handle user cancelling
throw ex;
}
}
Upvotes: 0
Views: 2361
Reputation: 3512
If you want to cancel an operation in the middle, you should use the async version, ExecuteAsync.
ExecuteAsync gets a cancelation token, so you can create a CancellationTokenSource, as described here: http://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx and cancel the operation in the middle.
Your code will look something like:
var tokenSource = new CancellationTokenSource();
cs.Events.Insert(e, "primary").ExecuteAsync(tokenSource).
ContinueWith( .... whatever you wish to continue with .... )
....
tokenSource.Cancel();
Upvotes: 1