Reputation: 44205
I would like to issue a SQL Server query (task1) and do some kind of monitoring in a loop (task2) while waiting for the query result. When task2 finds a certain condition is met, the query needs to be cancelled (I will use SQLCommand.Cancel()). This means either task2 can issue the cancel command, or signals task1 to cancel it. Either when the result is returned or the cancel happens, task2 ends and task1 continues executing to the end of the method.
What's an optimal and simple construct to use for this? TPL, Async/await, waithandles, events..? Using .NET 4.5 in a class (not UI).
Upvotes: 0
Views: 64
Reputation: 61736
It depends on further specifics. You can get it done with TPL (Task.WhenAny
, CancellationTokenSource
), async/await
and asynchronous TAP-based SQL APIs (e.g., SqlCommand.ExecuteNonQueryAsync
).
Or, depending on what conditions you monitor in task2 and how their changes are propogated, you could use Reactive Extensions.
Using low-level threads and synchronization primitives APIs would be a wrong choice, they should rarely be used with .NET 4+.
Upvotes: 1