繁体   English   中英

如何在C#中实现健壮的线程监视?

[英]How to implement robust thread monitoring in C#?

我有2个并行运行的任务,这是任务信息。 任务1-启动和运行应用程序任务2-监视应用程序的运行时间。 如果超过30分钟,则发出任务1应用程序的停止命令,然后重新启动两个任务。

任务1应用程序有点沉重,长时间运行会导致内存泄漏。

我要问的是,在这种情况下如何实现健壮的线程解决方案。

    using QuickTest;
    using System;
    using System.Threading;
    using System.Threading.Tasks;

    namespace TaskParallelExample
     {
     internal class Program
      {
       private static void Main(string[] args)
        {
        Parallel.Invoke(RunApplication, MonitorApplication);
    }

    private static void RunApplication()
    {
        Application uftInstance = new Application();
        uftInstance.Launch();
        QuickTest.Test uftTestInstance = uftInstance.Test;
        uftInstance.Open(@"C:\Tasks\Test1");
        uftInstance.Test.Run(); // It will may run more then 30 mins or less then also. It it exceeds 30 mins which is calculated from Monitor Application.
    }

    private static void MonitorApplication()
    {
        Application uftInstance = new Application();
        try
        {
            DateTime uftTestRunMonitor = DateTime.Now;
            int runningTime = (DateTime.Now - uftTestRunMonitor).Minutes;
            while (runningTime <= 30)
            {
                Thread.Sleep(5000);
                runningTime = (DateTime.Now - uftTestRunMonitor).Minutes;
                if (!uftInstance.Test.IsRunning)
                {
                    break;
                }
            }
        }
        catch (Exception exception)
        {
            //To-do
        }
        finally
        {
            if (uftInstance.Test.IsRunning)
            {
                //Assume it is still running and it is more then 30 mins
                uftInstance.Test.Stop();
                uftInstance.Test.Close();
                uftInstance.Quit();
            }
        }
    }
}

}

谢谢,拉姆

您能否将CancellationTokenSource的超时时间设置为30分钟?

var stopAfter30Mins = new CancellationTokenSource(TimeSpan.FromMinutes(30));

然后,您可以将其传递给worker方法:

var task = Task.Run(() => worker(stopAfter30Mins.Token), stopAfter30Mins.Token);

...

static void worker(CancellationToken cancellation)
{
    while (true)  // Or until work completed.
    {
        cancellation.ThrowIfCancellationRequested();
        Thread.Sleep(1000); // Simulate work.
    }
}

请注意,如果辅助任务无法定期检查取消状态,则没有可靠的方法来处理任务超时。

System.Threading.Tasks.Task完成任务

   CancellationTokenSource cts = new CancellationTokenSource();
            CancellationToken token = cts.Token;
            Task myTask = Task.Factory.StartNew(() =>
           {
               for (int i = 0; i < 2000; i++)
               {
                   token.ThrowIfCancellationRequested();

                   // Body of for loop.
               }
           }, token);

            //Do sometohing else 
            //if cancel needed
            cts.Cancel();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM