使用可能会挂起的API强制取消任务 [英] Force Cancel Task with API that might hang

查看:69
本文介绍了使用可能会挂起的API强制取消任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用串行端口,即使设置了自己的超时时间,我使用的API有时也会挂起读取.

这不是一个大问题,但是当发生这种情况并且挂机线程需要关闭时,我需要做一些工作.我已经尝试了以下方法,但是由于没有终止API调用,但是在其余代码继续执行并抛出TimeoutException的情况下继续执行,这一直给我带来了问题.在一段时间后如何使用Task取消挂起的任务?

CancellationToken token = new CancellationToken();
var task = Task.Factory.StartNew(() => 
           {
               CallingAPIThatMightHang(); // Example
           }, token);

if (!task.Wait(this.TimeToTimeOut, token))
{
    throw new TimeoutException("The operation timed out");
}

解决方案

很遗憾,我无法使用任何其他框架,并且我无法仅更改我正在调用的API,因此它可以使用取消令牌. /p>

这就是我选择解决问题的方式.

class Program
{
    static void Main(string[] args)
    {
        try
        {
            var result = TestThreadTimeOut();
            Console.WriteLine("Result: " + result);
        }
        catch (TimeoutException exp)
        {
            Console.WriteLine("Time out");
        }
        catch (Exception exp)
        {
            Console.WriteLine("Other error! " + exp.Message);
        }

        Console.WriteLine("Done!");
        Console.ReadLine();
    }

    public static string TestThreadTimeOut()
    {
        string result = null;
        Thread t = new Thread(() =>
        {
            while (true)
            {
                Console.WriteLine("Blah Blah Blah");
            }
        });
        t.Start();
        DateTime end = DateTime.Now + new TimeSpan(0, 0, 0, 0, 1500);
        while (DateTime.Now <= end)
        {
            if (result != null)
            {
                break;
            }
            Thread.Sleep(50);
        }
        if (result == null)
        {
            try
            {
                t.Abort();
            }
            catch (ThreadAbortException)
            {
                // Fine
            }
            throw new TimeoutException();
        }
        return result;
    }
}

I am currently working with a Serial Port, and the API I use will some times hang on a read, even when its own time out is set.

This is not a big problem, but i need to do some work when that happens and the hanging thread needs to be shutdown. I have tried that with the following, but it has been giving me problems as the API call is not terminated, but allowed to continue while the rest of the code continues, and the TimeoutException was thrown. How can i use Tasks to be able to cancel a hanging task after a certain amount of time?

CancellationToken token = new CancellationToken();
var task = Task.Factory.StartNew(() => 
           {
               CallingAPIThatMightHang(); // Example
           }, token);

if (!task.Wait(this.TimeToTimeOut, token))
{
    throw new TimeoutException("The operation timed out");
}

解决方案

I am sadly not able to use any other framework, and i am not able to just change the API i am calling so it can use a Cancellation Token.

This is how i chose to solve the problem.

class Program
{
    static void Main(string[] args)
    {
        try
        {
            var result = TestThreadTimeOut();
            Console.WriteLine("Result: " + result);
        }
        catch (TimeoutException exp)
        {
            Console.WriteLine("Time out");
        }
        catch (Exception exp)
        {
            Console.WriteLine("Other error! " + exp.Message);
        }

        Console.WriteLine("Done!");
        Console.ReadLine();
    }

    public static string TestThreadTimeOut()
    {
        string result = null;
        Thread t = new Thread(() =>
        {
            while (true)
            {
                Console.WriteLine("Blah Blah Blah");
            }
        });
        t.Start();
        DateTime end = DateTime.Now + new TimeSpan(0, 0, 0, 0, 1500);
        while (DateTime.Now <= end)
        {
            if (result != null)
            {
                break;
            }
            Thread.Sleep(50);
        }
        if (result == null)
        {
            try
            {
                t.Abort();
            }
            catch (ThreadAbortException)
            {
                // Fine
            }
            throw new TimeoutException();
        }
        return result;
    }
}

这篇关于使用可能会挂起的API强制取消任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆