我需要逐行详细解释下面的代码以及流程如何,例如,当我调试时.我刚刚在我的程序中使用了这个代码来避免a cross thread access error.代码工作正常,但这段代码是什么呢?
delegate void updateTextField(string Text);
private void updateText(string Text)
{
if (txtDelegate.InvokeRequired)
{
updateTextField del = new updateTextField(updateText);
txtDelegate.Invoke(del, new object[] { Text });
}
else
{
txtDelegate.Text = Text;
}
}
Run Code Online (Sandbox Code Playgroud)
此方法在以下情况下调用backgroundWorker_DoWork():
updateText("using delegate");
Run Code Online (Sandbox Code Playgroud)
我还需要代表们的解释.我读到了它,但我理解的是委托就像一个函数的指针,但我需要一个简单的例子清晰的解释.把我当成新手.
Laz*_*rus 13
// Declaring a delegate function kind of lifts the function away from the
// current object and the current thread, making it 'thread-safe' to call
// (although it may still not be thread-safe to execute).
delegate void updateTextField(string Text);
private void updateText(string Text)
{
// This asks the control if it's running on the same thread as this method is
// currently executing, i.e. can I update you directly or do I need to use
// the cross thread calling method "Invoke".
if (txtDelegate.InvokeRequired)
{
// Here we define the delegate function that's going to be Invoked.
// Here it's the same function were currently within but when it's invoked
// by the following line, it'll be done on the same thread as the control.
// At that point, InvokeRequired will return false and the other branch
// will be followed to update the actual text on the control.
updateTextField del = new updateTextField(updateText);
// Here we invoke the function passing in the Text we want to update the
// control with as a parameter.
txtDelegate.Invoke(del, new object[] { Text });
}
else
{
// When this function is Invoked, this is the branch that will be followed
// (as we're on the same thread as the control) and the text on the control
// will be replaced with the text passed in from the Invoke.
txtDelegate.Text = Text;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望更详细地介绍它,委托的实际机制是"线程安全的"超出了这个答案的范围.
| 归档时间: |
|
| 查看次数: |
1365 次 |
| 最近记录: |