相关疑难解决方法(0)

C#的隐藏功能?

在我从这个问题中学到以下内容后,我想到了这一点:

where T : struct
Run Code Online (Sandbox Code Playgroud)

我们C#开发人员都知道C#的基础知识.我的意思是声明,条件,循环,运算符等.

我们中的一些人甚至掌握了Generics,匿名类型,lambdas,LINQ等......

但是C#粉丝,瘾君子,专家几乎都不知道C#最隐藏的功能或技巧是什么?

以下是到目前为止显示的功能:


关键词

属性

c# hidden-features

1475
推荐指数
230
解决办法
68万
查看次数

C#事件和线程安全

UPDATE

从C#6开始,这个问题的答案是:

SomeEvent?.Invoke(this, e);
Run Code Online (Sandbox Code Playgroud)

我经常听到/阅读以下建议:

在检查事件之前,请务必复制事件null并将其触发.这将消除线程的潜在问题,其中事件变为null位于您检查null和触发事件的位置之间的位置:

// Copy the event delegate before checking/calling
EventHandler copy = TheEvent;

if (copy != null)
    copy(this, EventArgs.Empty); // Call any handlers on the copied list
Run Code Online (Sandbox Code Playgroud)

更新:我从阅读中了解到这可能还需要事件成员的优化,但Jon Skeet在他的回答中指出CLR不会优化副本.

但同时,为了解决这个问题,另一个线程必须做到这样的事情:

// Better delist from event - don't want our handler called from now on:
otherObject.TheEvent -= OnTheEvent;
// Good, now we can be certain that OnTheEvent will not run...
Run Code Online (Sandbox Code Playgroud)

实际的顺序可能是这种混合物:

// Copy the event delegate before checking/calling
EventHandler copy …
Run Code Online (Sandbox Code Playgroud)

c# events multithreading

230
推荐指数
6
解决办法
8万
查看次数

如何安全地开火活动

如果事件没有订阅者,我如何确保在触发事件时不会抛出异常.

 // Delegate declaration
 public delegate void _delDisplayChange(object sender,string option);

 // Event declaration
 public event _delDisplayChange  DisplayChange;

 //throwing the event
 DisplayChange(this, "DISTRIBUTION");
Run Code Online (Sandbox Code Playgroud)

c# events .net-2.0

2
推荐指数
1
解决办法
1093
查看次数

标签 统计

c# ×3

events ×2

.net-2.0 ×1

hidden-features ×1

multithreading ×1