[英]How to implement robust thread monitoring in C#?
I have 2 tasks running parallelly and here is the task information. 我有2个并行运行的任务,这是任务信息。 Task 1 - Launch and run application Task 2 - Monitor the application run duration. 任务1-启动和运行应用程序任务2-监视应用程序的运行时间。 If it exceeds 30 mins, issue a stop command of task 1 application and restart both task. 如果超过30分钟,则发出任务1应用程序的停止命令,然后重新启动两个任务。
Task 1 application bit heavy and memory leak prone during longer runs. 任务1应用程序有点沉重,长时间运行会导致内存泄漏。
I am requesting, how can we implement robust threading solution for this situation. 我要问的是,在这种情况下如何实现健壮的线程解决方案。
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();
}
}
}
}
} }
Thanks, Ram 谢谢,拉姆
Could you use a CancellationTokenSource
with timeout set to 30 mins? 您能否将CancellationTokenSource
的超时时间设置为30分钟?
var stopAfter30Mins = new CancellationTokenSource(TimeSpan.FromMinutes(30));
Then you would pass that to your worker method: 然后,您可以将其传递给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.
}
}
Note that if the worker task cannot periodically check the cancellation status, there is NO robust way to handle task timeout. 请注意,如果辅助任务无法定期检查取消状态,则没有可靠的方法来处理任务超时。
System.Threading.Tasks.Task do the job 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.