未完成后,在5秒后取消长时间运行的任务

时间:2017-03-30 11:38:52

标签: c# task cancellationtokensource cancellation-token

我创建了一个创建XML字符串的任务。该任务可以持续多秒。当任务在5秒后没有完成时,我想要“平滑地”取消任务并继续编写其余的XML。所以我在我的任务中建立了取消。但是我在日志中看到以下消息:

  • ProcessInformationTask超时

我也在日志中看到这一行

添加过程信息耗时10001毫秒

我想知道为什么会发生这种情况,因为我想在5秒后取消任务(如果没有完成)。所以我希望这项任务能够持续5秒钟。我怎么解决这个问题?可能是取消设置不正确吗?

我调用任务的代码

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;
} 

任务方法

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 个答案:

答案 0 :(得分:0)

我认为您应该在方法的每一步之后检查是否多次请求取消。以下是使用for循环的示例:

    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;
    }

如果在内部任务方法中调用其他方法,则可以将取消令牌传递给它们并在其中使用方法token.ThrowIfCancellationRequested()

        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
    }