Cancel long running Task after 5 seconds when not finished

北战南征 提交于 2021-01-27 19:21:19

问题


I have created a task which creates an XML string. The task can last multiple seconds. When the task isn't finished after 5 seconds, I want to cancel the Task 'smootly' and continue with writing the rest of the XML. So I built in cancellation inside my task. But although I see the following message in the Log:

  • ProcessInformationTask timed out

I also see this line in my log

Adding the process information took 10001 ms

I wonder why this can happen because I want to cancel the Task after 5 seconds (if not finished). So I expect the task to last 5 seconds max. How can I solve this? Probably the cancelation isn't setup properly?

Code where I call my task

string additionalInformation = null;
var contextInfo = new StringBuilder();

var xmlWriterSettings = new XmlWriterSettings()
{
    OmitXmlDeclaration = true,
    ConformanceLevel = ConformanceLevel.Fragment
};

var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;

using (XmlWriter xmlWriter = XmlWriter.Create(contextInfo, xmlWriterSettings))
{
    try
    {
        xmlWriter.WriteStartElement("AdditionalInformation");

        //Write xml (not long running)

        var watch = System.Diagnostics.Stopwatch.StartNew();
        string processInformation = AddProcessesInformation(xmlWriterSettings);
        watch.Stop();
        var elapsedMs = watch.ElapsedMilliseconds;
        Log.Info("Adding the process information took : " + elapsedMs + " ms");

        if (!string.IsNullOrEmpty(processInformation))
        {
            xmlWriter.WriteRaw(processInformation);
        }

        //Write xml (not long running)

        xmlWriter.WriteEndElement();

        additionalInformation = contextInfo.ToString();
    }

    catch (Exception e)
    {
        Log.Info("An exception occured during writing the additional information: " + e.Message);
        return false;
    }

    return true;
} 

Task method

private static string AddProcessesInformation(XmlWriterSettings xmlWriterSettings)
    {
        var tokenSource = new CancellationTokenSource();
        var token = tokenSource.Token;
        var contextInfo = new StringBuilder();

        var processInformationTask = Task<string>.Factory.StartNew(() =>
        {
            if (token.IsCancellationRequested)
            {
                Log.Info("Cancellation request for the ProcessInformationTask");
            }

            Thread.Sleep(10000);

            return "Ran without problems'";

        }, token);

        if (!processInformationTask.Wait(5000, token))
        {
            Log.Info("ProcessInformationTask timed out");
            tokenSource.Cancel();
        }

        return processInformationTask?.Result;
    }

回答1:


I think you should check if cancellation is requested multiple Times, after each step in your method. Here is example using for loop:

    private static string AddProcessesInformation(XmlWriterSettings xmlWriterSettings)
    {
        var tokenSource = new CancellationTokenSource();
        var token = tokenSource.Token;
        var contextInfo = new StringBuilder();

        var processInformationTask = Task<string>.Factory.StartNew(() =>
        {               
            for(int i = 0; i < 10; i++)
            {
                if (token.IsCancellationRequested)
                {
                    Console.WriteLine("Cancellation request for the ProcessInformationTask");
                    return string.Empty;
                }
                Thread.Sleep(1000);
            }

            return "Ran without problems'";

        }, token);

        if (!processInformationTask.Wait(5000, token))
        {
            Console.WriteLine("ProcessInformationTask timed out");
            tokenSource.Cancel();
        }

        return processInformationTask?.Result;
    }

If inside task method you call other methods, you can pass cancellation token to them and use method token.ThrowIfCancellationRequested() inside.

        var processInformationTask = Task<string>.Factory.StartNew(() =>
        {
            try
            {
                Method1(token);
                Thread.Sleep(1000);
                Method2(token);
                Thread.Sleep(1000);
            }
            catch(OperationCanceledException ex)
            {
                return string.Empty;
            }
            return "Ran without problems'";

        }, token);


    private static void Method1(CancellationToken token)
    {
        token.ThrowIfCancellationRequested();
        // do more work
    }


来源:https://stackoverflow.com/questions/43116824/cancel-long-running-task-after-5-seconds-when-not-finished

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!