Doyen
Doyen

Reputation: 11

C# Debug build ok, but Release build fail due to optimized

It seems due to compiler optimization:(.net 4.0, VS2015), This is a background worker for touch panel.

DispatchService.BeginInvoke(() =>
{
    _vm = new TouchViewModel(Container.GetExportedValue<ITouchView>());
    _vm.ShowDialog();
});

// the background worker waiting for the Dialog show up
while (_vm == null) ; // Trace.WriteLine($"Wait _vm");
// Get Packet from Touch Panel
_vm.Points.Add(packet);
// (draw on the dialog via data binding)

it works at "Debug" build, but forever loop at "Release" build. If add Trace.WriteLine in the while loop, it works too. What is the right approach to solve it?

No await/async because WinXP compatible(.NET 4.0)

Upvotes: 0

Views: 107

Answers (1)

Sinatr
Sinatr

Reputation: 21969

If you need to block execution until delegate will be executed in some other thread then implementing a proper synchronization is a key.

To example, you can use Monitor:

// field somewhere
readonly object _lock = new object();

// then
DispatchService.BeginInvoke(() =>
{
    _vm = new TouchViewModel(Container.GetExportedValue<ITouchView>());
    lock(_lock)
        Monitor.Pulse(_lock);
    _vm.ShowDialog();
});
lock(_lock)
    Monitor.Wait(_lock);    

Upvotes: 1

Related Questions