none
Need to cancel an async task while blocking method is called RRS feed

  • Question

  • Assume a simple task which is running asynchronously and may stay forever waiting for a blocking call which never returns.

    I.e. normally it will return after a while, but depending on external conditions it might never return.

    I want to cancel the task based on some event (e.g. operator action), but don't know how I can use the cancellation token to interrupt the blocking call and thereby perform neccessary actions.

    Anyone has a simple sample/explanation?

    Saturday, January 6, 2018 12:04 PM

All replies

  • Hi EuroEager,

    Thank you for posting here.

    For your question, you could refer to the MSDN article. It shows how to cancel an Async Task with examples.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, January 10, 2018 12:51 AM
    Moderator
  • As far as I can see the article only handles cases where non-blocking calls are used.

    More specifically for my case:
    My program sits in a tight loop doing (by PInvoke) a call to (Kernel32.dll) ReadFile()
    I do not use overlapping because my program has to be maximum accurate timing-wise (each byte read shall be logged with a timestamp in the microseconds range by using QueryPerformanceCounter (actually Stopwatch which is a wrapper around it) and I assume that accuracy is lost and perhaps ruined if I use overlapping read (which introduces thread context switch?).
    A.f.a.i.k. CancelIO cannot be used for non-overlapping read operations.
    So if my assumptions are correct I have to use the blocking version and I have no idea of how to terminate the loop if necessary (Thread.Abort or Interrupt doesn't work because blocking call).

    I hope it is possible without killing the process (which would ruin my byte logging because all data will be lost)

    Thursday, January 11, 2018 5:15 PM
  • Please, any more suggestions?
    Sunday, February 25, 2018 9:26 PM