如何取消超时后螺纹 [英] How to cancel the thread after timeout

查看:162
本文介绍了如何取消超时后螺纹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多线程的应用程序,我使用的来控制节数的过程(2)。欲处理文件仅用于指定的持续时间。下面是我的做法。我得到的的CancellationTokenSource已被释放。错误。

如果我不是dispoing的 cts.Dispose(); 那么过程是不是10秒后弯腰。它是继续处理,直到1000任何一个可以帮助我在这里。

注意:我有一个1000个文件。要求是处理文件,在给定的时间(10秒),通过控制过程的数目(2)之间,(有些X的毫秒)睡眠中

下面是我的code

 类节目
{
    静态无效的主要(字串[] args)
    {
        尝试
        {
            LimitedConcurrencyLevelTask​​Scheduler LCTS =新LimitedConcurrencyLevelTask​​Scheduler(2);
            清单<任务>任务=新的List<任务>();
            TaskFactory厂=新TaskFactory(LCTS);
            CancellationTokenSource CTS =新CancellationTokenSource();            的for(int i = 0; I< 1000;我++)
            {
                INT I1 = I;
                VAR T = factory.StartNew(()=>
                {
                    如果(CTS!= NULL)
                        Console.WriteLine({0} - {1},I1,GetGuid(cts.Token));
                },cts.Token);                tasks.Add(T);
            }            Task.WaitAll(tasks.ToArray(),10000,cts.Token);
            cts.Dispose();
            Console.WriteLine(\\ n \\ nSuccessful完成。);
            到Console.ReadLine();
        }
        赶上(异常前)
        {
            Console.WriteLine(ex.Message);
        }
    }    私有静态的Guid GetGuid(的CancellationToken cancelToken)
    {
        如果(cancelToken.IsCancellationRequested)
        {
            返回Guid.Empty;
        }
        Thread.sleep代码(TimeSpan.FromSeconds(1));
        返回Guid.NewGuid();
    }
}


解决方案

你可以做的是,你可以运行一个任务,将你的取消标记状态更改为一段时间后取消。

这样的:

 类节目
{
    公共静态无效ProcessFiles(的CancellationToken CTS)
    {
        尝试
        {
            LimitedConcurrencyLevelTask​​Scheduler LCTS =新LimitedConcurrencyLevelTask​​Scheduler(2);
            清单<任务>任务=新的List<任务>();
            TaskFactory厂=新TaskFactory(LCTS);            的for(int i = 0; I< 1000;我++)
            {
                INT I1 = I;
                VAR T = factory.StartNew(()=>
                {
                    如果(CTS =空!)Console.WriteLine({0} --- {1},I1,GetGuid());
                },CTS);                tasks.Add(T);
            }            Task.WaitAll(tasks.ToArray());            Console.WriteLine(\\ n \\ nSuccessful完成。);
            到Console.ReadLine();
        }
        赶上(异常前)
        {
            Console.WriteLine(ex.Message);
        }
    }    静态无效的主要(字串[] args)
    {
        CancellationTokenSource CTS =新CancellationTokenSource();
        Task.Factory.StartNew(()=> {Thread.sleep代码(10000); cts.Cancel();});
        ProcessFiles(cts.Token);
        Console.ReadKey();
    }    私有静态的Guid GetGuid()
    {
        Thread.sleep代码(TimeSpan.FromSeconds(1));
        返回Guid.NewGuid();
    }
}

I have a multi-threaded application and i'm using this to control the no.of processes (2). I want to process files only for specified time duration. Below is my approach. I'm getting The CancellationTokenSource has been disposed. error.

If i'm not dispoing the cts.Dispose(); then the process is not stooping after 10 sec. It is keep on processing till 1000. Can any one help me here.

Note: I've a 1000 files. Requirement is process files with in a given time (10 sec) by controlling the number of process (2) and sleep in between (some x ms).

Below is my code

class Program
{
    static void Main(string[] args)
    {
        try
        {
            LimitedConcurrencyLevelTaskScheduler lcts = new LimitedConcurrencyLevelTaskScheduler(2);
            List<Task> tasks = new List<Task>();
            TaskFactory factory = new TaskFactory(lcts);
            CancellationTokenSource cts = new CancellationTokenSource();

            for (int i = 0; i < 1000; i++)
            {
                int i1 = i;
                var t = factory.StartNew(() =>
                {
                    if (cts != null)
                        Console.WriteLine("{0} --- {1}", i1, GetGuid(cts.Token));
                }, cts.Token);

                tasks.Add(t);
            }

            Task.WaitAll(tasks.ToArray(), 10000, cts.Token);
            cts.Dispose();
            Console.WriteLine("\n\nSuccessful completion.");
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    private static Guid GetGuid(CancellationToken cancelToken)
    {
        if (cancelToken.IsCancellationRequested)
        {
            return Guid.Empty;
        }
        Thread.Sleep(TimeSpan.FromSeconds(1));
        return Guid.NewGuid();
    }
}

解决方案

What you can do is you can run a Task that will change your Cancellation Token state to canceled after some time.

Like this :

class Program
{
    public static void ProcessFiles(CancellationToken cts)
    {            
        try
        {                
            LimitedConcurrencyLevelTaskScheduler lcts = new LimitedConcurrencyLevelTaskScheduler(2);
            List<Task> tasks = new List<Task>();
            TaskFactory factory = new TaskFactory(lcts);                

            for (int i = 0; i < 1000; i++)
            {
                int i1 = i;
                var t = factory.StartNew(() =>
                {
                    if (cts != null) Console.WriteLine("{0} --- {1}", i1, GetGuid());
                }, cts);

                tasks.Add(t);
            }

            Task.WaitAll(tasks.ToArray());

            Console.WriteLine("\n\nSuccessful completion.");
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    static void Main(string[] args)
    {
        CancellationTokenSource cts = new CancellationTokenSource();
        Task.Factory.StartNew(() => { Thread.Sleep(10000); cts.Cancel(); });
        ProcessFiles(cts.Token);
        Console.ReadKey();
    }

    private static Guid GetGuid()
    {
        Thread.Sleep(TimeSpan.FromSeconds(1));
        return Guid.NewGuid();
    }
}

这篇关于如何取消超时后螺纹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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