serhio
serhio

Reputation: 28586

VolatileWrite booleans

Where is the problem?

bool stillSingleClick = false;

// does not compime
System.Threading.Thread.VolatileWrite(ref stillSingleClick, true); 

The best overloaded method match for 'System.Threading.Thread.VolatileWrite(ref object, object)' has some invalid arguments

Why do I ask.. I try to differentiate my doubleClick in the following way:

volatile bool stillSingleClick = false;

void SegmentLine_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    SegmentLine line = sender as SegmentLine;

    if (e.ClickCount == 1)
    {
        stillSingleClick = true;

        Thread thread = new Thread(
            new System.Threading.ThreadStart(
                delegate()
                {
                    line.Dispatcher.Invoke(
                        System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(
                            delegate()
                            {
                                Thread.Sleep(System.Windows.Forms.SystemInformation.DoubleClickTime * 2);
                                if (stillSingleClick) // HERE ALWAYS TRUE!!!
                                {
                                    SelectSegmentLine(line);
                                }
                                stillSingleClick = false;
                            }
                    ));
                }
        ));
        thread.Start();
    }
    else if (e.ClickCount == 2)
    {
        stillSingleClick = false; // HERE SHOULD BE SET IN FALSE !!!
        DisplaySegmentLineInfo(line);
    }
}

Does not work stillSingleClick is always in True....

Upvotes: 1

Views: 412

Answers (4)

Danilo Garcia
Danilo Garcia

Reputation: 1

VolativeWrite has no overload for boolean.

Upvotes: 0

Henrik
Henrik

Reputation: 23324

I think your real problem is that Thread.Sleep should be put before the call to Invoke, not inside. I'm guessing line.Dispatcher.Invoke executes the action on the UI thread. So the second click will set stillSingleClick to false only after the action finished.

Upvotes: 2

cdhowie
cdhowie

Reputation: 169028

VolatileWrite has no overload for operating on bool variables. I have had this same problem with the Interlocked class. My workaround was to use an int instead, using 0 for false and 1 for true. It's a nasty hack, but it works.

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500875

There are no overloads for VolatileWrite for Boolean fields, basically.

Any reason not to just use a volatile field to start with? Or you could use a field of a different type, as cdhowie suggested.

Personally I get nervous trying to write lock-free code. It's so easy to get wrong. Are there any alternatives to your current design using higher-level building blocks? If you're using .NET 4, the new Tasks Parallel Library can be very useful.

Upvotes: 2

Related Questions