我有一个函数,它消耗资源(CPU和时间),我需要它始终运行(同时为true),但是我想要一个选项来等待\暂停(但仅函数可以等待而不是线程) )。 我试图创建一个运行线程的任务,所以soi将能够在线程上进行设置和重置时等待任务完成。 代码如下。 它不起作用,因为任务结束时没有等待线程被设置\重置。
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private static ConcurrentDictionary<int, Task> waitingTasks = new ConcurrentDictionary<int, Task>();
private static ConcurrentDictionary<int, ManualResetEvent> manualResetEvents = new ConcurrentDictionary<int, ManualResetEvent>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Timers.Timer timer;
timer = new System.Timers.Timer(60000);
timer.Elapsed += Timer_Elapsed;
whileTrue(1);
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (false)// some condition
{
releasePerPrefix(1);
}
}
private void whileTrue(int index)
{
while (true)
{
if (true)// some condition
{
Task waiting = getWaitingTask(index);
Console.WriteLine("start waiting " + DateTime.Now);
waiting.Wait();
///HERE IS THE PROBLEAM - the waiting task continue imedialty without it being halt\wait\pause
Console.WriteLine("Released "+DateTime.Now);
}
doJob();
}
}
private void doJob()
{
Console.WriteLine("doJob " + DateTime.Now);
}
private Task getWaitingTask(int prefix)
{
if (!waitingTasks.TryGetValue(prefix, out Task task) || task.IsCompleted)
{
task = Task.Factory.StartNew(() =>
{
Thread thread = new Thread(new ThreadStart(() => waitPerPrefix(prefix)));
thread.Start();
thread.Join();
});
waitingTasks.TryAdd(prefix, task);
}
return task;
}
private static void waitPerPrefix(int prefix)
{
if (!manualResetEvents.TryGetValue(prefix, out ManualResetEvent manualResetEvent))
{
manualResetEvent = new ManualResetEvent(false);
manualResetEvents.TryAdd(prefix, manualResetEvent);
}
manualResetEvent.Reset();
}
private static void releasePerPrefix(int prefix)
{
if (!manualResetEvents.TryGetValue(prefix, out ManualResetEvent manualResetEvent))
{
manualResetEvent = new ManualResetEvent(true);
manualResetEvents.TryAdd(prefix, manualResetEvent);
}
manualResetEvent.Set();
}
}
}