1.Dynamics CRM 365控制并发的处理方式:
方法一:在CRM创建实体(在数据库端控制,设置唯一聚集索引来处理)
步骤1:新增实体scw_entitylock,删除所有索引,新增唯一聚集索引idx_scw_name【scw_name】
步骤2:代码例子:LockEntity函数
public void LockEntity(IOrganizationService adminservice, string lockid,Action action) { try { Entity en = new Entity("scw_entitylock"); en["scw_name"] = lockid; adminservice.Create(en); action(); } catch (Exception ex) { throw new InvalidPluginExecutionException("抱歉,系统正忙,请重新保存。"); } finally { QueryExpression qe = new QueryExpression("scw_entitylock"); qe.Criteria.AddCondition("scw_name", ConditionOperator.Equal, lockid); var ec = adminservice.RetrieveMultiple(qe); if (ec != null && ec.Entities.Count > 0) { adminservice.Delete("scw_entitylock", ec.Entities[0].Id); } } }
步骤3:调用方式:
LockEntity(adminService, "xxxxxxxxx", () => { //do your code });
温馨提示:上面的模式只支持Plugin、workflow中使用,因为他们自带事务,才能在adminservice.Create(en);实现等待。
方法二:SQL的写法:那表scw_entitylock就可以不用实体的,直接新增表。
Begin Tran Insert Into scw_entitylock(scw_name) Select 'xxxxx'
方法三:在进程端处理:这个方案经过验证:发现另个用户同时在Plugin触发的时候,并没有效果
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp3 { class Program { static void Main(string[] args) { Thread th = new Thread(new ParameterizedThreadStart(thread1)); th.Name = "111"; Thread th1 = new Thread(new ParameterizedThreadStart(thread2)); th1.Name = "222"; Thread th2 = new Thread(new ParameterizedThreadStart(thread3)); th2.Name = "333"; th.Start("11"); th1.Start("11"); th2.Start("11"); Console.ReadKey(); } static void Done(object name) { Console.WriteLine("开始执行" + Thread.CurrentThread.Name); lock (name.ToString()) { Console.WriteLine("进入休眠区" + Thread.CurrentThread.Name); Thread.Sleep(20000); Console.WriteLine("推出休眠区"+ Thread.CurrentThread.Name); } } static void thread1(object name) { Done(name); } static void thread2(object name) { Done(name); } static void thread3(object name) { Done(name); } } }