当我没有可用的控件时如何调用()

本文关键字:何调用 调用 控件 | 更新日期: 2023-09-27 18:02:32

我正在编写一个连接处理程序(一个请求用户名和密码的对话框)。代码是一个显示对话框的处理程序。这段代码可以从线程中调用,所以我需要Invoke()如果InvokeRequired

在理想的情况下,我可以用Control初始化处理程序来做InvokeRequired,但有时控件可能为空。这可能吗?我如何实现代码?以下是正确的吗?

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
    }

}

我的问题是:

  1. 如果我传递一个null控件给InitializeMethod()
  2. 会发生什么
  3. 如果Initialize()方法在线程中执行,代码稍后会工作吗?
  4. 如果您没有任何控制来测试InvokeRequired,推荐的模式是什么?

Thanks in advance


编辑:做一些测试,我已经意识到,如果我通过零Initialize(), UI线程中运行的控制并不因此InvokeRequired似乎返回false。总是这样。所以我的问题是,当我没有控制权时,我如何执行一个真正的(可)调用?


EDIT2:做mInvokeControl.CreateControl()修复问题

当我没有可用的控件时如何调用()

在这个类上实现ISynchronizeInvoke。下面是一个例子:

public class GuiCredentialsHandler : ISynchronizeInvoke
{
        //....
        private readonly System.Threading.SynchronizationContext _currentContext = System.Threading.SynchronizationContext.Current;
        private readonly System.Threading.Thread _mainThread = System.Threading.Thread.CurrentThread;
        private readonly object _invokeLocker = new object();
        //....

        #region ISynchronizeInvoke Members
        public bool InvokeRequired
        {
            get
            {
                return System.Threading.Thread.CurrentThread.ManagedThreadId != this._mainThread.ManagedThreadId;
            }
        }
        /// <summary>
        /// This method is not supported!
        /// </summary>
        /// <param name="method"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        [Obsolete("This method is not supported!", true)]
        public IAsyncResult BeginInvoke(Delegate method, object[] args)
        {
            throw new NotSupportedException("The method or operation is not implemented.");
        }
        /// <summary>
        /// This method is not supported!
        /// </summary>
        /// <param name="method"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        [Obsolete("This method is not supported!", true)]
        public object EndInvoke(IAsyncResult result)
        {
            throw new NotSupportedException("The method or operation is not implemented.");
        }
        public object Invoke(Delegate method, object[] args)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }
            lock (_invokeLocker)
            {
                object objectToGet = null;
                SendOrPostCallback invoker = new SendOrPostCallback(
                delegate(object data)
                {
                    objectToGet = method.DynamicInvoke(args);
                });
                _currentContext.Send(new SendOrPostCallback(invoker), method.Target);
                return objectToGet;
            }
        }
        public object Invoke(Delegate method)
        {
            return Invoke(method, null);
        }
        #endregion//ISynchronizeInvoke Members
}

注意:由于类实现使用System.Threading.SynchronizationContext.Current,所以你可以在WindowsFormswpf中使用它,但不能在控制台应用程序中使用它,因为System.Threading.SynchronizationContext.Current是空的。

一个简单的解决方案是在主线程中创建一个不可见的控件,您的工作线程可以在此控件上调用Invoke