如何立即取消curl操作? [英] How can I immediately cancel a curl operation?

查看:546
本文介绍了如何立即取消curl操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中使用 libcurl ,我正在调用 curl_easy_perform 使用 Boost.Thread 与我的用户界面分离。 / p>

主UI有一个取消按钮,我想要完美的响应(即,当用户点击它,它应该立即作出反应)。我有读,写和进度回调设置读取原子 should_cancel 变量(如



  1. 偶尔,有一个很长的时间(有时是无休止的)延迟。在这种情况下,可以:



    a。进度,读取和写入回调只是不被长时间调用,或



    b。调用进度回调,我返回一个非零值(意味着它应该终止),但curl操作不会完成一段时间(实际上,进度函数在此期间再次调用!)


因此:


  1. 为什么会出现长时间延迟(特别是没有调用进度功能)?

  2. 我应该怎么做才能允许取消按钮正常?

一种可能性是告诉UI取消操作成功,但在后台保持运行curl线程直到取消。这个问题(我认为)是,它强制 should_cancel 变量是全局的,而不是作用域到操作开始的对话框。

你的基本想法是对的。您应该从UI中分离curl操作。但是,实现应该改变一点。您不应该使用全局 should_cancel 。相反,您应该有一个请求的全局 current_request 指针。这个类型应该有一个内部 cancel 标志和一个公共 Cancel()函数。响应取消按钮,在 current_request 上调用取消,然后将其为空。



您需要小心使用您的互斥体,以防止您的互斥体僵尸对象。取消和请求完成之间存在固有的竞争条件。


I'm using libcurl in C++, and I'm calling curl_easy_perform in a separate thread from my UI using Boost.Thread.

The main UI has a cancel button that I'd like to be perfectly responsive (i.e., when a user clicks on it, it should immediately react). I have read, write, and progress callbacks set up to read an atomic should_cancel variable (as in this question), but there are two problems:

  1. There's often a very small (but noticeable) delay from when cancel is pressed to when the curl operation completes.

  2. Occasionally, there's a very long (sometimes interminable) delay. In this case, either:

    a. the progress, read, and write callbacks simply aren't called for a long time, or

    b. the progress callback is called, I return a nonzero value (meaning it should terminate), but the curl operation doesn't complete for a while longer (in fact, the progress function is called again in the meantime!)

So:

  1. Why do the long delays happen (especially without calling the progress function)?
  2. What should I do instead to allow the cancel button to react properly?

One possibility is to tell the UI that the cancel operation succeeded, but keep running the curl thread in the background until it cancels. The problem with this (I think) is that it forces the should_cancel variable to be global, instead of scoped to the dialog box where the operation began.

解决方案

Your basic idea is right. You should detach the curl operation from the UI. However, the implementation should be changed a bit. You shouldn't be using a global should_cancel. Instead, you should have a global current_request pointer, to an object of type Request. This type should have an internal cancel flag, and a public Cancel() function. In response to the cancel button, you call Cancel on the current_request and then null it. A cancelled request is then repsonsible for its own cleanup at a later time (it's a thread, after all).

You'll need to be careful with your mutexes to prevent zombie objects. There's an inherent race condition between a cancel and a request completion.

这篇关于如何立即取消curl操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆