相关疑难解决方法(0)

在这种常见模式中是否存在用于防止NullReferenceException的竞争条件?

我问了这个问题并得到了这个有趣(并且有点令人不安)的答案.

Daniel在他的回答中指出(除非我读错了)ECMA-335 CLI规范允许编译器生成抛出NullReferenceException以下DoCallback方法的代码.

class MyClass {
    private Action _Callback;
    public Action Callback { 
        get { return _Callback; }
        set { _Callback = value; }
    }
    public void DoCallback() {
        Action local;
        local = Callback;
        if (local == null)
            local = new Action(() => { });
        local();
    }
}
Run Code Online (Sandbox Code Playgroud)

他说,为了保证NullReferenceException不抛出,volatile关键字应该用于_Callbacklock应该在线周围使用local = Callback;.

有人可以证实这一点吗?而且,如果确实如此,Mono.NET编译器之间在这个问题上的行为是否存在差异?

编辑
这是标准的链接. …

.net c# il multithreading thread-safety

25
推荐指数
1
解决办法
985
查看次数

CancellationTokens如何保证是最新的?

微软给出了这个例子CancellationToken是.NET 4中使用.

using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
    static void Main()
    {

        var tokenSource2 = new CancellationTokenSource();
        CancellationToken ct = tokenSource2.Token;

        var task = Task.Factory.StartNew(() =>
        {

            // Were we already canceled?
            ct.ThrowIfCancellationRequested();

            bool moreToDo = true;
            while (moreToDo)
            {
                // Poll on this property if you have to do
                // other cleanup before throwing.
                if (ct.IsCancellationRequested)
                {
                    // Clean up here, then...
                    ct.ThrowIfCancellationRequested();
                }

            }
        }, tokenSource2.Token); // Pass same token to …
Run Code Online (Sandbox Code Playgroud)

.net c# multithreading task-parallel-library cancellation-token

5
推荐指数
1
解决办法
1953
查看次数