Now there is a scenario where the server sends a task to 10 clients, and after all the clients have finished executing, the entire task is executed.
After each client executes, a completed message is sent over HTTP to the server, and the server sends an email notification to the user.
When 10 clients send a complete request at the same time, the client list results from the server query from the database are not completed and may send 1~10 messages.
The workaround is to add an object lock to the task ID.
//result Query lock dictionary, lock according to ID, when all the devices are completed, this lock object can be discarded Private Staticdictionary<Long,Object> task_res_lockers =Newdictionary<Long,Object>(); Public ObjectGetlocker (LongtaskId) { if(!task_res_lockers. ContainsKey (taskId)) {Task_res_lockers[taskid]=NewObject (); } returnTask_res_lockers[taskid]; } Public voidRemovelock (LongtaskId) { if(task_res_lockers. ContainsKey (taskId)) {task_res_lockers. Remove (TASKID); } }
When the client returns execution results
Lock (Agentresultdao.getlocker (taskId)) { // Process Task completion logic // when the task is completed Agentresultdao.removelock (taskId) Release object reference
The lock keyword is actually a syntax sugar for the Monitor class
BOOL false ; Try { ref acquiredlock); // Code that accesses resources is protected by the lock. }finally{ if (acquiredlock) { Monitor.Exit ( lockobject);} }
C # Object Lock