boost :: asio :: steady_timer停止触发

时间:2019-05-31 01:10:53

标签: c++ timer boost-asio

我编写了以下小的测试驱动程序,以测试另一个Windows应用程序中的某些鼠标事件。

由于某种原因,它会在触发的第5次或第6次左右停止触发。如果我在回调中放置一个断点并在遇到击打时恢复运行,那么它将正常工作。

它没有任何异常或失败代码。我只是在Visual Studio输出窗口中看到两个线程退出。

我想念什么?

#include <boost/asio.hpp>
#include "boost/asio/deadline_timer.hpp"
#include<boost/bind.hpp>
#include <chrono>
#include <iostream>

class Pooper
{
    boost::asio::io_context & m_ioContext;
    boost::asio::steady_timer m_timer;

public:
    Pooper(boost::asio::io_context & ioContext)
        :
        m_ioContext(ioContext)
        , m_timer(boost::asio::steady_timer(ioContext))
    {
    }

    void Run()
    {
        m_timer.expires_from_now(std::chrono::seconds(5));
        m_timer.async_wait(boost::bind(&Pooper::OnTimerExpired, this, boost::asio::placeholders::error));
    }

    void OnTimerExpired(const boost::system::error_code & error)
    {
        if (error.failed())
        {
            std::cerr << "boost error: Failed" << std::endl;
        }

        std::cout << "Poop" << std::endl;

        try
        {
            // Move the mouse
            int x = 500;
            int y = 500;
            if (!::SetCursorPos(x, y))
            {
                int errorCode = GetLastError();
                std::cerr << "SetCursorPos error: " << errorCode << std::endl;
            }

            // Left button down
            x = 65536 * 500;
            y = 65536 * 500;
            ::mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN, x, y, NULL, NULL);

            // Left button up
            x = 65536 * 500;
            y = 65536 * 500;
            ::mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTUP, x, y, NULL, NULL);

            m_timer.expires_from_now(std::chrono::seconds(5));
            m_timer.async_wait(boost::bind(&Pooper::OnTimerExpired, this, boost::asio::placeholders::error));
        }
        catch (std::exception &)
        {
            std::cerr << "An exception occured." << std::endl;
        }
    }
};

int main()
{
    boost::asio::io_context ioContext;
    auto pooper = Pooper(ioContext);
    pooper.Run();
    ioContext.run();

    std::cerr << "Exited..." << std::endl;
}

0 个答案:

没有答案