溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C#多線程異步執(zhí)行和跨線程訪問控件Helper怎么用

發(fā)布時(shí)間:2022-04-24 10:12:04 來源:億速云 閱讀:170 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“C#多線程異步執(zhí)行和跨線程訪問控件Helper怎么用”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“C#多線程異步執(zhí)行和跨線程訪問控件Helper怎么用”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。

一、工具類代碼

    public class TaskHelper
    {

        #region 多線程操作
        /// <summary>
        /// 功能描述:多線程執(zhí)行方法,方法無參數(shù),無返回值
        /// </summary>
        /// <param name="func">方法,如果方法中調(diào)用了控件,請(qǐng)使用 ThreadInvokerControl(() => { 您的操作})進(jìn)行包括</param>
        /// <param name="callback">執(zhí)行完成回調(diào),參數(shù)為object,如果錯(cuò)誤返回的是Exception,否則為null,如果為空則默認(rèn)調(diào)用基類回調(diào)方法</param>
        /// <param name="enableControl">調(diào)用線程時(shí)禁用的控件</param>
        public static void TaskRun(
          Form frm,
          Func<Task> func,
          Action<object> callback = null,
          Control[] enableControl = null)
        {
            if (enableControl != null)
            {
                SetControlEnableds(enableControl, false);
            }

            Task.Factory.StartNew(() =>
            {
                try
                {
                    Task task = func();
                    if (task.Exception != null && task.Exception.InnerException != null)
                        throw task.Exception.InnerException;
                    callback?.Invoke(null);
                }
                catch (Exception ex)
                {
                    if (callback != null)
                        callback(ex);
                    else
                        ThreadBaseCallBack(frm, ex);
                }
                finally
                {
                    if (enableControl != null && frm != null)
                        ThreadInvokerControl(frm, () => { SetControlEnableds(enableControl, true); });
                }
            });
        }

        /// <summary>
        /// 功能描述:線程默認(rèn)回調(diào)方法
        /// </summary>
        public static void ThreadBaseCallBack(Form frm, Exception ex)
        {
            if (frm != null)
            {
                ThreadInvokerControl(frm, () =>
                {
                    try
                    {
                        Exception lastEx = ex.GetOriginalException();
                        MessageBox.Show(lastEx.Message);
                    }
                    catch
                    {

                    }
                });
            }
        }

        /// <summary>
        /// 功能描述:委托調(diào)用,用于夸線程訪問控件
        /// </summary>
        /// <param name="action">action</param>
        /// <param name="f">所在窗體,默認(rèn)使用當(dāng)前窗體</param>
        public static void ThreadInvokerControl(Form frm, Action action)
        {
            if (frm != null)
            {
                if (frm.InvokeRequired)
                {
                    frm.BeginInvoke(action);
                }
                else
                {
                    action();
                }
            }
        }

        #endregion

        #region 提示層
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        private static void ShowProcessPanel(Control parent, string strMessage)
        {
            if (parent.InvokeRequired)
            {
                parent.BeginInvoke(new MethodInvoker(delegate
                {
                    ShowProcessPanel(parent, strMessage);
                }));
            }
            else
            {
                parent.VisibleChanged -= new EventHandler(parent_VisibleChanged);
                parent.VisibleChanged += new EventHandler(parent_VisibleChanged);
                parent.FindForm().FormClosing -= ControlHelper_FormClosing;
                parent.FindForm().FormClosing += ControlHelper_FormClosing;
                Control control = null;
                lock (parent)
                {
                    control = HaveProcessPanelControl(parent);
                    if (control == null)
                    {
                        control = CreateProgressPanel();
                        parent.Controls.Add(control);
                    }
                }
                FWaiting fWaiting = control.Tag as FWaiting;
                fWaiting.Message = strMessage;
                fWaiting.Show();
            }
        }
        private static void ControlHelper_FormClosing(object sender, FormClosingEventArgs e)
        {
            Control control = sender as Control;
            control.FindForm().FormClosing -= ControlHelper_FormClosing;
            CloseWaiting(control);
        }

        private static void parent_VisibleChanged(object sender, EventArgs e)
        {
            Control control = sender as Control;
            control.VisibleChanged -= new EventHandler(parent_VisibleChanged);
            if (!control.Visible)
            {
                CloseWaiting(control);
            }
        }
        private static void CloseWaiting(Control control)
        {
            Control[] array = control.Controls.Find("myProgressPanelext", false);
            if (array.Length > 0)
            {
                Control myProgress = array[0];
                if (myProgress.Tag != null && myProgress.Tag is FWaiting)
                {
                    FWaiting fWaiting = myProgress as FWaiting;
                    if (fWaiting != null && !fWaiting.IsDisposed && fWaiting.Visible)
                    {
                        fWaiting.Hide();
                    }
                }
            }
        }
        private static void CloseProcessPanel(Control parent)
        {
            if (parent.InvokeRequired)
            {
                parent.BeginInvoke(new MethodInvoker(delegate
                {
                    CloseProcessPanel(parent);
                }));
            }
            else if (parent != null)
            {
                Control control = HaveProcessPanelControl(parent);
                if (control != null)
                {
                    Form frm = control.Tag as Form;
                    if (frm != null && !frm.IsDisposed && frm.Visible)
                    {
                        if (frm.InvokeRequired)
                        {
                            frm.BeginInvoke(new MethodInvoker(delegate
                            {
                                frm.Hide();
                            }));
                        }
                        else
                        {
                            frm.Hide();
                        }
                    }
                }
            }
        }
        private static Control HaveProcessPanelControl(Control parent)
        {
            Control[] array = parent.Controls.Find("myProgressPanelext", false);
            Control result;
            if (array.Length > 0)
            {
                result = array[0];
            }
            else
            {
                result = null;
            }
            return result;
        }
        private static Control CreateProgressPanel()
        {
            return new Label
            {
                Name = "myProgressPanelext",
                Visible = false,
                Tag = new FWaiting
                {
                    TopMost = true,
                }
            };
        }
        #endregion

        #region 禁用控件時(shí)不改變空間顏色
        [System.Runtime.InteropServices.DllImport("user32.dll ")]
        private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int wndproc);
        [System.Runtime.InteropServices.DllImport("user32.dll ")]
        private static extern int GetWindowLong(IntPtr hWnd, int nIndex);

        private const int GWL_STYLE = -16;
        private const int WS_DISABLED = 0x8000000;

        /// <summary>
        /// 功能描述:設(shè)置控件的Enable屬性,控件不改顏色
        /// </summary>
        /// <param name="c">c</param>
        /// <param name="enabled">enabled</param>
        private static void SetControlEnabled(Control c, bool enabled)
        {
            if (enabled)
            {
                SetWindowLong(c.Handle, GWL_STYLE, (~WS_DISABLED) & GetWindowLong(c.Handle, GWL_STYLE));
            }
            else
            {
                SetWindowLong(c.Handle, GWL_STYLE, WS_DISABLED + GetWindowLong(c.Handle, GWL_STYLE));
            }
        }

        /// <summary>
        /// 功能描述:設(shè)置多個(gè)控件的Enable屬性,控件不改顏色
        /// </summary>
        /// <param name="cs">cs</param>
        /// <param name="enabled">enabled</param>
        private static void SetControlEnableds(Control[] cs, bool enabled)
        {
            foreach (var c in cs)
            {
                SetControlEnabled(c, enabled);
            }
        }
        #endregion
    }

二、調(diào)用代碼

            TaskHelper.TaskRun(this, async () =>
            {
                TaskHelper.ThreadInvokerControl(this, () =>
                {
                    //夸線程訪問控件的
                    this.btnStart.Enabled = true;
                    this.btnStart.BackColor = Color.Gainsboro;
                });
            });

讀到這里,這篇“C#多線程異步執(zhí)行和跨線程訪問控件Helper怎么用”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI