我正在编写一个连接处理程序(一个请求用户名和密码的对话框)。该代码是一个显示对话框的处理程序。可以从线程调用此代码,因此我需要Invoke()
if InvokeRequired
。
Control
在理想情况下,我可以使用to do初始化 then 处理程序InvokeRequired
,但有时 Control 可能为空。是否可以?我该如何实现代码?以下是正确的吗?
public class GuiCredentialsHandler
{
// control used to invoke if needed
private static Control mInvokeControl;
/// <summary>
/// Initialize a GetCredentials handler for current process.
/// This method should be always called from the main thread, for
/// a correctly handling for invokes (when the handler is called
/// from a thread).
/// </summary>
/// <param name="parentControl">Application top form.
/// Can be null if unknown</param>
public static void Initialize(Control parentControl)
{
if (parentControl != null)
{
mInvokeControl = parentControl;
}
else
{
mInvokeControl = new Control();
// force to create window handle
mInvokeControl.CreateControl();
}
}
public static Credentials GetCredentials()
{
if (mInvokeControl.InvokeRequired)
{
return mInvokeControl.Invoke(
new GetCredentialsDelegate(DoGetCredentials), null)
as Credentials;
}
else
{
return DoGetCredentials();
}
}
private static Credentials DoGetCredentials()
{
// the code stuff goes here
}
}
我的问题是:
- 如果我将空控件传递给
InitializeMethod()
- 如果在UIThread中执行了Initialize()方法,后面的代码会起作用吗?
- 如果您没有任何控制来测试,推荐的模式是什么
InvokeRequired
?
提前致谢
编辑:做一些测试,我意识到如果我将 null 传递给Initialize()
,则控件不会在 UI 线程中运行,因此 InvokeRequired 似乎返回 false。总是。所以我的问题是,当我无法控制时,如何执行真正的(可变的)调用?
EDIT2:mInvokeControl.CreateControl()
解决问题。