gpt4 book ai didi

c# - 不推荐使用的成员变量

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

根据MSDN ,由于线程和缓存,不建议使用成员变量。请注意,这个问题涉及多个领域,虽然我确定它主要与 .NET/C# 相关,但它可能结果特定于 CRM。它可能不会,但单挑可能是明智的。

虽然我对可能出现的问题了如指掌,但我不完全确定我理解准确和精确的情况,这些情况超出警告的范围。我关心的确切报价如下。

For improved performance, Microsoft Dynamics CRM 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.

我的类(class)是按照以下原则构建的。

public partial class Blopp : IPlugin
{
private IPluginExecutionContext Context { get; set; }
private Entity Target { get; set; }
private IOrganizationService Service { get; set; }
...

public Blopp() : this(String.Empty) { }
public Blopp(String a) : this(a, String.Empty) { }
public Blopp(String a, String b) { ... }

public void Execute(IServiceProvider serviceProvider)
{
try
{
Assign(serviceProvider);
DoStuff();
}
catch (Exception) { }
finally { ... }
}

private void Assign(IServiceProvider serviceProvider) { ... }
}

现在,这个问题可能看起来很愚蠢,但是提到的全局变量 - 我的privatenon-static 字段不知何故是全局的?我会说他们不是,但我最近有点偏执,我想保持谦虚。

此外,当我访问上下文并分配字段时,我创建了一个新对象并一个一个地分配字段(不是每个类都有方法克隆) .序列化将要求我继承原始类,这违反了要求。这是一种足够可靠的方法吗? (请记住我新获得的偏执狂。)

我曾尝试在我的执行过程中造成问题,但据我所知,问题并没有出现。当然,没有证据并不是不存在的证据。我只是指出我不是懒惰发帖。而是意识到在比我最初看到的更深层次上的东西可能是错误的。

最佳答案

不,私有(private)成员不是全局变量。关键点是“您不应使用全局变量尝试将任何数据存储在成员变量中以便在下一次插件调用期间使用”

它表示,如果您在 Execute() 中操作您的私有(private)(或全局)变量,则 Execute() 的另一个调用可能会在同一实例上运行同时覆盖您的私有(private)(或全局)变量,导致在此之后运行的代码显示意外行为。

所以,让它们成为局部变量:

private void Assign(IServiceProvider serviceProvider) 
{
IPluginExecutionContext context;
Entity target;
IOrganizationService service;

...
}

这将确保每个调用堆栈只访问它自己的变量。

关于c# - 不推荐使用的成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30506673/

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