gpt4 book ai didi

c# - Timer Elapsed 事件如何与高优先级线程竞争?

转载 作者:行者123 更新时间:2023-11-30 16:33:20 25 4
gpt4 key购买 nike

我有一个要使用的 System.Timers.Timer 对象,但我不希望绑定(bind)到 Timer 的处理干扰普通到高优先级线程。换句话说,我想说我想每 5 秒处理一次 X,只要没有其他东西在运行

我如何确保我的计时器操作以低优先级方式运行?

最佳答案

System.Timers.Timer 的好处是您可以通过 SynchronizingObject 属性分配一个同步对象,然后利用它来运行 Elapsed 事件优先级可控。

只需将 ElapsedEventReceiver 的实例分配给计时器的 SynchronizingObject 属性即可。

免责声明:我很快就完成了这个,所以您需要添加自己的收尾工作以使其更加健壮。

public class ElapsedEventReceiver : ISynchronizeInvoke
{
private Thread m_Thread;
private BlockingCollection<Message> m_Queue = new BlockingCollection<Message>();

public ElapsedEventReceiver()
{
m_Thread = new Thread(Run);
m_Thread.Priority = ThreadPriority.BelowNormal;
m_Thread.IsBackground = true;
m_Thread.Start();
}

private void Run()
{
while (true)
{
Message message = m_Queue.Take();
message.Return = message.Method.DynamicInvoke(message.Args);
message.Finished.Set();
}
}

public IAsyncResult BeginInvoke(Delegate method, object[] args)
{
Message message = new Message();
message.Method = method;
message.Args = args;
m_Queue.Add(message);
return message;
}

public object EndInvoke(IAsyncResult result)
{
Message message = result as Message;
if (message != null)
{
message.Finished.WaitOne();
return message.Return;
}
throw new ArgumentException("result");
}

public object Invoke(Delegate method, object[] args)
{
Message message = new Message();
message.Method = method;
message.Args = args;
m_Queue.Add(message);
message.Finished.WaitOne();
return message.Return;
}

public bool InvokeRequired
{
get { return Thread.CurrentThread != m_Thread; }
}

private class Message : IAsyncResult
{
public Delegate Method;
public object[] Args;
public object Return;
public object State;
public ManualResetEvent Finished = new ManualResetEvent(false);

public object AsyncState
{
get { return State; }
}

public WaitHandle AsyncWaitHandle
{
get { return Finished; }
}

public bool CompletedSynchronously
{
get { return false; }
}

public bool IsCompleted
{
get { return Finished.WaitOne(0); }
}
}
}

关于c# - Timer Elapsed 事件如何与高优先级线程竞争?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3312004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com