Search code examples
multithreadingwindows-store-appsc++-cx

How correctly cancel LoadAsync after some timeout


Consider that I am using thread, which reads data stream from network socket (Windows::Networking::Sockets::StreamSocket) with help of Windows::Storage::Streams::DataReader (m_reader). I need to stop this thread and it waits mostly in LoadAsync. How to correctly cancel LoadAsync method after some timeout?

auto t1 = create_task(m_reader->LoadAsync(sizeof(len)));
t1.wait();

I tried several ways but none worked correctly. Or I can't use DataReader and I must choose some other approach?


Solution

  • Your call t1.wait(); is a blocking call that will throw an exception if the LoadAsync call fails for some reason. In your case, that HRESULT is ERROR_OPERATION_ABORTED, which is pretty much what I would expect ("The I/O operation has been aborted because of either a thread exit or an application request.")

    What you could do is create a task cancellation token, attach it to your task, and then fire the token cancellation when desired.

    From https://technet.microsoft.com/en-us/office/hh780559:

    //Class member:
    cancellation_token_source m_fileTaskTokenSource;
    
    // Cancel button event handler:
    m_fileTaskTokenSource.cancel();
    
    // task chain
    auto getFileTask2 =
      create_task(documentsFolder->GetFileAsync(fileName), 
                                     m_fileTaskTokenSource.get_token()); 
    

    Note: calling cancel on the cancellation token will cause the the task to throw a task_canceled exception, so you will need to catch and handle that exception.