How to cancel boost asio io_service post

boost, boost-asio, c++, post

Solution

You cannot selectively cancel callbacks in such a manner through an `io_service`. One option is to move the logic to a higher level, such as inside of `MyClass`. A sample implementation may be:

class MyClass : public boost::enable_shared_from_this<MyClass>
{
public:
    typedef boost::shared_ptr<MyClas> Ptr;
    static Ptr create( boost::asio::io_service& io_service ) { 
        const Ptr result( new MyClass );
        io_service.post( boost::bind(&MyClass::myCallback, result) );
        return result;
    }

    void myCallback() { 
        if ( _canceled ) return;
    }

    void cancel() { _canceled = true; }

private:
    MyClass() : _canceled(false) { }

private:
    bool _canceled;
};

This class uses a `boost::shared_ptr` to enforce shared ownership semantics. Doing this gurantees the object lifetime will persist as long as the callback remains in the `io_service` queue before being dispatched.

Problem

How can I cancel already posted callback: ``` getIoService()->post(boost::bind(&MyClass::myCallback, this)); ``` and keep other posted callbacks untouched? The problem is that I have some object that receives events from different thread and I post them to ioservice in order to handle events in main thread. What if at some point I want to delete my object - ioservice will try to execute already posted callbacks in destroyed object. And in this case I can't store any flag in object since it will be removed. There is a possible solution to use `enable_shared_from_this` and `shared_from_this()`, but wondering whether another solution or not. Thanks

Original source