gpt4 book ai didi

c# - MS CRM 插件。 C#如何保证关键 block 的单次执行?

转载 作者:太空宇宙 更新时间:2023-11-03 17:30:15 24 4
gpt4 key购买 nike

首先,我在 Microsoft Dynamics CRM 插件代码中遇到了一个奇怪的问题。

这是我的代码示例:

public class Counter : Plugin
{
private static object Locker = new object();

public Counter() : base(typeof(Counter))
{
....
}

public void GenerateNumber(LocalPluginContext localContext)
{
IOrganizationService service = localContext.OrganizationService;
IPluginExecutionContext context = localContext.PluginExecutionContext;

Entity Target = (Entity)context.InputParameters["Target"];

var Number=0;
lock(Locker)
{
var CounterEntity = service.GetCounterEntity();

Number=(int)CounterEntity["number"];
CounterEntity["number"]=Number+1;

service.Update(CounterEntity);
}

Target["number"]=Number;
service.Update(Entity);
}
}

据我了解,每次创建某个实体时,系统都会创建 Counter 实例并执行 GenerateNumber 方法。Counter 的实例应该从 Counter 实体中获取最后一个数字,增加它并将其保存到数据库中。但不知何故,这段代码生成了两次相同的数字。

如果计数器在不同的线程中创建,那么 lock 应该完成他的工作。

为什么会这样,我该如何解决这个问题?我应该用信号量替换锁吗?

最佳答案

平台不会在每次执行插件时都创建一个新的插件实例。每the SDK :

For improved performance, Microsoft Dynamics 365 caches plug-in instances. The plug-in's Execute method should be written to be stateless because the constructor is not called for every invocation of the plug-in. Also, multiple system threads could execute the plug-in at the same time. All per invocation state information is stored in the context, so you should not use global variables or attempt to store any data in member variables for use during the next plug-in invocation unless that data was obtained from the configuration parameter provided to the constructor. Changes to a plug-ins registration will cause the plug-in to be re-initialized.

您试图解决的问题经常被错误地解决。在线发布的许多解决方案都存在您面临的相同问题,当许多记录大约同时创建时,会生成重复的自动编号。我最喜欢(而且绝对正确)的两个理解这个问题的资源是:

关于c# - MS CRM 插件。 C#如何保证关键 block 的单次执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41690323/

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