I have a form and some control on it :
public class Tester : Form
{
public Label Demo;
public Label GetDemo()
{
return Demo.Text;
}
}
Also I have some static class :
public static bool Delay(Func<bool> condition)
{
bool result = false;
AutoResetEvent e = new AutoResetEvent(false);
Timer t = new Timer(delegate {
if (result = condition()) e.Set(); // wait until control property has needed value
}, e, 0, 1000);
e.WaitOne();
t.Dispose();
return result;
}
At some point control creates new thread and calls our static method :
ThreadPool.QueueUserWorkItem(delegate {
if (Delay(() => GetDemo() == "X")) MessageBox.Show("X");
}, null);
Of course, this will cause an exception because GetDemo will be passed to Delay and will be called in a new thread as a delegate.
Of course, it is possible to solve it by using Invoke to call our static method :
ThreadPool.QueueUserWorkItem(delegate {
Invoke((MethodInvoker) delegate {
if (Delay(() => GetDemo() == "X")) MessageBox.Show("OK");
}
}, null);
Unfortunately, i am not allowed to change call of Delay, i can change only its implementation.
Question :
1) what needs to be changed INSIDE static method Delay so that condition() would executed GetDemo in its native thread without exceptions?
2) is it possible to do something like this inside Delay?
SynchronizationContext.Dispatcher((Action) delegate {
if (condition()) e.Set();
});