How to cancel HostingEnvironment.QueueBackgroundWorkItem

Is there any way to cancel the background job with HostingEnvironment.QueueBackgroundWorkItem?

There is CancellationTokenone that notifies you if tasks have been canceled, but how can I do this? Referring to https://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx

Successful cancellation includes requesting code calling the CancellationTokenSource.Cancel method

OK Where can i access CancellationTokenSource?

+2
source share
2 answers

After several trials, I came up with this thought:

HostingEnvironment.QueueBackgroundWorkItem(ct =>
{
    var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(ct);
    var cancellationToken = linkedTokenSource.Token;
    return Task.Factory.StartNew(() =>
    {
         // do stuff on background
    }, cancellationToken);
});

Update:

Indeed, the task is not needed. Thanks svick for this. Here is a slightly more detailed example of code without a task.

HostingEnvironment.QueueBackgroundWorkItem(ct =>
{
    var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(ct);
    // following is a dummy method, but you get the idea.
    // StoreCancellationTokenSourceSoItCanBeUsedSomewhereElse(linkedTokenSource);

    var cancellationToken = linkedTokenSource.Token;

    try
    {
        while(true)
        {
            cancellationToken.ThrowIfCancellationRequested();
            // do bg stuff
        }
    }
    catch (OperationCanceledException ex)
    {
        // either token is in cancelled state
    }
});
+2
source

HostingEnvironment.QueueBackgroundWorkItem:

public static void QueueBackgroundWorkItem(Action<CancellationToken> workItem)

, CancellationToken. , . :

CancellationToken , .

workItem - , CancellationToken, CancellationTokenSource. , , 10 :

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));

HostingEnvironment.QueueBackgroundWorkItem(_ =>
{
    cts.Token.ThrowIfCancellationRequested();

    // the code of the work item goes here
});

, CancellationToken , .

, . , , CancellationToken.

+1

Source: https://habr.com/ru/post/1671657/


All Articles