如何取消在Google API.NET中执行/执行异步()调用

本文关键字:执行 异步 调用 NET Google 何取消 取消 API | 更新日期: 2023-09-27 18:27:49

我使用带有.NET库的Google API。我正在构建一个安装了Windows的应用程序,如果时间过长,我希望允许用户取消。有人能给我看一些示例C#代码来取消Execute()或ExecuteAsync()调用吗?我正在一个单独的线程中运行所有API通信。那个API线程将检查一个全局变量,看看它是否应该停止,但如果那个单独的线程被困在Execute()上,我该如何停止它?我希望有一种更优雅的方法,只需在线程上调用Abort()。这里有一些伪代码:

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 },
        "johndoe@gmail.com",
        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;
    }
}

如何取消在Google API.NET中执行/执行异步()调用

如果您想取消中间的操作,您应该使用异步版本ExecuteAsync。

ExecuteAsync获取一个取消令牌,因此您可以创建一个CancellationTokenSource,如下所述:http://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx,并取消在中间的操作。

你的代码看起来像:

var tokenSource = new CancellationTokenSource();
cs.Events.Insert(e, "primary").ExecuteAsync(tokenSource).
     ContinueWith( .... whatever you wish to continue with .... )
....
tokenSource.Cancel();