-1

If I continuously launch several Task.Run(method) that may block, is there a way to discover (or cache for later cancelling) the tasks that are blocked waiting for example for a lock{}, or a Waitone() inside method ?

So for example, if I say:

Task.Run(() =>               
{
    TradingSystem.QuoteUpdate(quote); //QuoteUpdate may block for several reasons
});

How do I later cancel only those tasks that are executing exactly the method TradingSystem.QuoteUpdate and have not run to completion?

Ivan
  • 7,448
  • 14
  • 69
  • 134
  • `TradingSystem.QuoteUpdate` sounds IO-bound. Is there a reason why you can't make this `async`? Either way, cancellation is _cooperative_ (normally done via a `CancellationToken`). – ProgrammingLlama Jul 02 '19 at 00:58
  • I may not be understanding you. How does your response address the issue that I need to cancel all Tasks with a specific method that were launched by Task.Run and maybe blocked? – Ivan Jul 02 '19 at 00:59
  • And yes, QuoteUpdate is the terminal method of getting a quote from a network packet. But I don't know how that is relevant in this case. – Ivan Jul 02 '19 at 01:01
  • 1
    See Alexei's answer. Hopefully that clears up what I was getting at. That's why I wondered if you could make `TradingSystem.QuoteUpdate` async to the point of IO-bound work (database calls, network calls, etc.), or to a point where a cancellation token is useful (a long loop, for example) – ProgrammingLlama Jul 02 '19 at 01:01
  • To abort a thread or task from outside the code that is running is a terrible idea. What state would you leave it in? It wouldn’t even have a chance to dispose anything. Instead, modify the method itself to check its own progress and gracefully time out if needed. – John Wu Jul 02 '19 at 03:07

1 Answers1

4

There is no way to list "all tasks", even less "all tasks executing particular method". So you need to store them at creation time if you need to iterate over them later.

Cancelation actually does not require you to know the task as you can pass same cancelation token to all tasks of that kind - see How to cancel a Task in await?.

But... that's not going to help you as task cancellation is cooperative activity and tasks blocked on lock or any other waits will not be able to cancel themselves. See How do I cancel a Blocked Task in C# using a Cancellation Token? and similar posts about hacks people try to work around that restriction. Basically there is nothing you can safely do except to make your code truly async and cancelable throughout all calls.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179