我有一个长时间运行的进程将数据发送到另一台机器。但是这些数据是分块接收的(比如一组 100 个数据包,然后延迟至少 10 秒)。
我在一个单独的线程上启动了发送功能
Task.Run(() => { SendPackets(); });
要发送的数据包Queue<Packet>由某个其他功能在一个对象中排队。
在SendPackets()我使用 while 循环来检索和发送(异步)队列中的所有可用项目。
void SendPackets()
{
while(isRunning)
{
while(thePacketQueue.Count > 0)
{
Packet pkt = thePacketQueue.Dequeue();
BeginSend(pkt, callback); // Actual code to send data over asynchronously
}
Task.Delay(1000); // <---- My question lies here
}
}
Run Code Online (Sandbox Code Playgroud)
所有的锁都到位了!
我的问题是,当我使用 时Task.Delay,下一个循环是否可能由与当前循环不同的线程执行?
有没有其他方法,而不是指定 1 秒的延迟,我可以使用类似的东西ManualResetEvent,以及相应的代码是什么(我不知道如何使用ManualResetEvent等。
另外,我是 async/await 和 TPL 的新手,所以请容忍我的无知。
TIA。
c# asynchronous manualresetevent task-parallel-library async-await