问题描述
我正在编写一个连接处理程序(一个请求用户名和密码的对话框).该代码是显示对话框的处理程序.可以从线程中调用此代码,因此如果InvokeRequired
,则需要Invoke()
.
I'm writing a connection handler (a dialog to request username and password). The code is a handler that shows a dialog. This code could be called from a thread, so I need to Invoke()
if InvokeRequired
.
在理想情况下,我可以使用Control
初始化处理程序以执行InvokeRequired
,但是有时Control可以为null.是否有可能?如何实现代码?以下正确吗?
In a ideal situation I can initialize then handler with a Control
to do InvokeRequired
, but sometimes the Control could be null. Is it possible? How could I implement the code? Is the following correct?
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
,推荐的模式是什么?
- What happens if I pass a null control to the
InitializeMethod()
- If the Initialize() method is executed in the UIThread, will the code work later?
- What is the recommended pattern if you havn't got any control to test
InvokeRequired
?
预先感谢
EDIT :做一些测试,我意识到如果将null传递给Initialize()
,则该控件未在UI线程中运行,因此InvokeRequired似乎返回false.总是.所以我的问题是,当我无法控制时如何执行真正的(可靠的)调用?
EDIT: Doing some tests, I have realized that if I pass null to Initialize()
, the control is not running in the UI thread so the InvokeRequired seems to return false. Always. So my question is, how can I perform a real (fiable) Invoke when I have no control?
EDIT2 :进行mInvokeControl.CreateControl()
解决了该问题.
EDIT2: Doing mInvokeControl.CreateControl()
fixs the issue.
推荐答案
一个简单的解决方案是在主线程中创建一个不可见的控件,您的工作线程可以在该控件上调用Invoke
.
A simple solution is to create an invisible control in the main thread on which your worker threads can call Invoke
.
这篇关于没有可用控件时如何调用()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!