简体   繁体   English

反编译程序集 - 不寻常的代码

[英]Decompiled assembly - unusual code

I decompiled an assembly using ILSpy, and one class in particular got my attention: 我使用ILSpy反编译了一个程序集,特别是一个类引起了我的注意:

public class CustomTextStream : NetworkStream
{
    private EventHandler<CustomEventArgs> someEvent;
    public event EventHandler<CustomEventArgs> SomePublicEvent
    {
        add
        {
            EventHandler<CustomEventArgs> eventHandler = this.someEvent;
            EventHandler<CustomEventArgs> eventHandler2;
            do
            {
                eventHandler2 = eventHandler;
                EventHandler<CustomEventArgs> value2 = 
                    (EventHandler<CustomEventArgs>)Delegate.Combine(eventHandler2, value);
                eventHandler = 
                    Interlocked.CompareExchange<EventHandler<CustomEventArgs>>(
                    ref this.someEvent, value2, eventHandler2);
            }
            while (eventHandler != eventHandler2);
        }
        remove
        {
            // similar stuff...
        }
    }
}

Further in the code, seems like private delegate is used to fire an actual event: 在代码中,似乎私有委托用于触发实际事件:

if (something != null && somethingElse != 0)
{
    this.someEvent(this, new CustomEventArgs(someArg));
}

The question: Can someone guess what could be the idea behind this custom accessors, assuming that some "compile/decompile magic" didn't take place? 问题:假设某些“编译/反编译魔法”没有发生,有人可以猜出这个自定义访问器背后的想法是什么吗? I'm not much familiar with IL, btw... 我对IL不是很熟悉,顺便说一下......

(Side note: the application is multi-threaded and utilizes networking, obviously.) (旁注:应用程序是多线程的,显然利用网络。)

This is a new event handler code generated by compiler. 这是由编译器生成的新事件处理程序代码。 It was introduced in C# 4 (C# 3 version was different) 它是在C#4中引入的(C#3版本不同)

Interlocked.CompareExchange compares first argument with third, and if they are equal, replaces first argument with second. Interlocked.CompareExchange将第一个参数与第三个参数进行比较,如果它们相等,则将第一个参数替换为第二个参数。 This is a thread-safe operation. 这是一个线程安全的操作。 Loop is used for a case when after assigning a variable eventHandler2 and before check, another thread changes this delegate. 循环用于在分配变量eventHandler2之后和检查之前,另一个线程更改此委托的情况。 In this case, Interlocked.CompareExchange does not perform exchange, loop condition does not evaluate to true and next attempt is made. 在这种情况下,Interlocked.CompareExchange不执行交换,循环条件不会计算为true并进行下一次尝试。

C# 3 generated simple code in event handlers: C#3在事件处理程序中生成了简单的代码:

add { lock(this) { changed = changed + value; } }

Which had lower performance and could introduce deadlocks. 哪个性能较低,可能会引入死锁。

There is a great series of articles on this subject: 关于这个主题有很多文章:

Events get a little overhaul in C# 4 事件在C#4中进行了一些改革

Events get a little overhaul in C# 4, Part II 事件在C#4,第二部分进行了一些改革

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM