我有两个并行运行的任务,这是任务信息。 任务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();
}
}
}
}
}
谢谢, 拉姆
答案 0 :(得分:1)
你可以使用超时设置为30分钟的CancellationTokenSource
吗?
var stopAfter30Mins = new CancellationTokenSource(TimeSpan.FromMinutes(30));
然后你会把它传递给你的工人方法:
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.
}
}
请注意,如果工作人员任务无法定期检查取消状态,则没有强大的方式来处理任务超时。
答案 1 :(得分:0)
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();