簡體   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