如何在超时后取消线程

时间:2015-07-24 06:19:08

标签: c# asp.net multithreading

我有一个多线程应用程序,我正在使用this来控制no.of进程(2)。我想只在指定的持续时间内处理文件。以下是我的方法。我收到已取消CancellationTokenSource。错误。

如果我没有对cts.Dispose();进行调度,则该过程在10秒后不会弯腰。它一直处理到1000.任何人都可以帮助我。

注意:我有1000个文件。要求是在给定时间(10秒)内通过控制进程数(2)和睡眠之间(某些x毫秒)的进程文件。

以下是我的代码

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

1 个答案:

答案 0 :(得分:1)

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

像这样:

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