I have had recently one of those really bad interviews, where they play good cop/bad cop with you. Whatever I replied wasn't good enough for one of them and my confidence was shrinking minute by minute. His final question that really confused me was the following:
if a control would need InvokeRequired would there be a difference in doing .Invoke or .BeginInvoke?
Let me show you an example, how I understand it:
public delegate string WorkLongDelegate(int i);
var del = new WorkLongDelegate(WorkLong);
var callback = new AsyncCallback(CallBack);
del.BeginInvoke(3000, callback, del);
public string WorkLong(int i)
{
Thread.Sleep(i);
return (string.Format("Work was done within {0} seconds.", i));
}
private void CallBack(IAsyncResult ar)
{
var del = (WorkLongDelegate) ar.AsyncState;
SetText2(del.EndInvoke(ar));
}
private void SetText2(string s)
{
if(InvokeRequired)
{
// What is the difference between BeginInvoke and Invoke in below?
BeginInvoke(new MethodInvoker(() => textBox1.Text = s));
}
else
{
textBox1.Text = s;
}
}
I mentioned that BeginInvoke would do it asynchronously while Invoke would be halting the UI thread until its executed. But that wasn't good enough. Nonetheless, I don't understand the performance implication in here if I used an Invoke instead. May someone please enlighten me?
Invoke
is vulnerable to deadlocks depending on your thread-safety setup – Settlings