Stopping a task without a CancellationToken

后端 未结 3 1574
我寻月下人不归
我寻月下人不归 2020-12-19 04:22

I am using an external library that has async methods, but not CancellationToken overloads.

Now currently I am using an extension method fr

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 04:44

    The only way I can think of is to change the TaskScheduler and mange the creation of the threads that are used for the tasks yourself. That is a lot of work.

    The basic concept is to create your own implementation of the TaskScheduler, start a new task with your own scheduler assigned. This way you get your scheduler to be the current one and start your problematic task from this task.

    There are still reason that may not work. If the task causing you trouble creates more tasks using the default task scheduler you still got the same problem. (Task.Run does so)

    How ever if they are using the async/await key words your scheduler will remain active.

    Now with the scheduler under your own control, you can kill any task by using Thread.Abort.

    To get a idea about the implementation afford, you should have a look at the ThreadPoolTaskScheduler. That is the default implementation of the scheduler.

    As I said this is a lot of work, but the only way I can think of to kill task that can't be cancelled.

    To get a test running if that even works at all you may only want to implement the behaviour the ThreadPoolTaskScheduler has for the TaskCreationOptions.LongRunning option. So spawning a new thread for each task.

提交回复
热议问题