为什么不能一个局部变量在C#挥发

为什么不能一个局部变量在C#挥发

本文介绍了为什么不能一个局部变量在C#挥发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public void MyTest()
{
  bool eventFinished = false;

  myEventRaiser.OnEvent += delegate { doStuff(); eventFinished = true; };
  myEventRaiser.RaiseEventInSeperateThread()

  while(!eventFinished) Thread.Sleep(1);

  Assert.That(stuff);
}



为什么不能eventFinished挥发和关系呢?

Why can't eventFinished be volatile and does it matter?

这似乎对我来说,在这种情况下,编译器或运行时可能成为智能其自身良好,并在同时循环eventFinished只能是假知道。尤其是当你考虑的方式解除变量被作为类的成员,并委托作为同一类的方法和的事实,eventFinished曾经是一个局部变量,从而剥夺了优化产生的。

It would seem to me that in this case the compiler or runtime could become to smart for its own good and 'know' in the while loop that eventFinished can only be false. Especially when you consider the way a lifted variable gets generated as a member of a class and the delegate as a method of that same class and thereby depriving optimizations of the fact that eventFinished was once a local variable.

推荐答案

有存在线程原始,的做正是这个任务 - 你不想使用布尔标志为

There exists a threading primitive, ManualResetEvent to do precisely this task - you don't want to be using a boolean flag.

这样的事情应该做的工作:

Something like this should do the job:

public void MyTest()
{
    var doneEvent = new ManualResetEvent(false);

    myEventRaiser.OnEvent += delegate { doStuff(); doneEvent.Set(); };
    myEventRaiser.RaiseEventInSeperateThread();
    doneEvent.WaitOne();

    Assert.That(stuff);
}



关于缺乏支持挥发性关键字局部变量,我不相信有任何理由,这可能不是在理论上是的可能的在C#。最有可能的,所以不能简单地,因为没有事先为C#2.0使用了这样的功能的支持。现在,随着匿名方法和LAMDA功能的存在,这种支持可能会成为有用的。有人请澄清问题,如果我失去了一些东西。

Regarding the lack of support for the volatile keyword on local variables, I don't believe there is any reason why this might not in theory be possible in C#. Most likely, it is not supported simply because there was no use for such a feature prior to C# 2.0. Now, with the existence of anonymous methods and lamda functions, such support could potentially become useful. Someone please clarify matters if I'm missing something here.

这篇关于为什么不能一个局部变量在C#挥发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:22