本文介绍了反编译组件 - 寻常code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我反编译使用ILSpy的组件,特别是一级了我的注意:

I decompiled an assembly using ILSpy, and one class in particular got my attention:

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...
        }
    }
}

此外,在code,恍如私人委托来触发一个真实的事件:

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...

(边注:该应用程序是多线程的,并利用网络,很明显)

(Side note: the application is multi-threaded and utilizes networking, obviously.)

推荐答案

这是由编译器生成一个新的事件处理程序code。它在C#4(C#3的版本是不同的)

This is a new event handler code generated by compiler. It was introduced in C# 4 (C# 3 version was different)

Interlocked.CompareExchange比较第一个参数与第三,如果他们是平等的,替换第二个第一个参数。这是一个线程安全的操作。循环用于为变量赋值时eventHandler2和检查之前之后,另一个线程改变了这一委托的情况。在这种情况下,Interlocked.CompareExchange不执行交换,循环条件不计算为真,下一个尝试。

Interlocked.CompareExchange compares first argument with third, and if they are equal, replaces first argument with second. 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. In this case, Interlocked.CompareExchange does not perform exchange, loop condition does not evaluate to true and next attempt is made.

C#3的事件处理程序生成的简单code:

C# 3 generated simple code in event handlers:

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得到一个小大修在C#4

Events得到一个小大修在C#4,第II部分

这篇关于反编译组件 - 寻常code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 00:13