繁体   English   中英

我怎样才能保存这个调用线程?

[英]How can I make this call thread save?

我正在使用在此页面上找到的自定义消息框,包括来源: https ://www.c-sharpcorner.com/blogs/creating-customized-message-box-with-animation-effect-in-windows-form

在大多数情况下,它工作正常,但有时当我同时弹出 2 个消息框时,此功能就会崩溃:

 class MsgBox : Form
 {

    private static MsgBox _msgBox;

    public static MsgDlgResult Show(string message, string title, Buttons buttons, IconImage icon)
    {
        _msgBox = new MsgBox();
        _msgBox._lblMessage.Text = message;
        _msgBox._lblTitle.Text = title;

        MsgBox.InitButtons(buttons);
        MsgBox.InitIcon(icon);

        _msgBox.Size = MsgBox.MessageSize(message);
        _msgBox.ShowDialog();
        MessageBeep(0);
        return _buttonResult;
    }

    private static void ButtonClick(object sender, EventArgs e)
    {
        Button btn = (Button)sender;

        switch (btn.Name)
        {
            case "Abort":
                _buttonResult = MsgDlgResult.Abort;
                break;

            case "Retry":
                _buttonResult = MsgDlgResult.Retry;
                break;

            ......

        }


       ----->>>> _msgBox.Dispose();
     }
 }

我收到错误消息 System.InvalidOperationException:“跨线程操作无效:从创建它的线程以外的线程访问控制”

如何使此类线程安全或至少在 c# 中进行此调用? 但它必须仍然能够让我一次拥有多个消息框。

更新我的通话:

 MessageBoxResult result = MsgBox.Show("My Message test", string.Empty, MsgBox.Buttons.OK, MsgBox.IconImage.Error);

让我猜猜...

  • 您创建第一个对话框并将其分配给_msgBox变量。
  • 然后创建第二个对话框,并再次将其分配给同一个_msgBox变量(因为它是static )。
  • 您单击第一个对话框中的按钮
  • 事件句柄触发并尝试处理第二个对话框
  • 你得到例外

此解决方案中的私有变量不应设为静态。 如果它们是静态的 - 此类的所有实例都引用变量的同一个实例,这里指的是相同的_msgBox_buttonResult

确保在调用静态Show时调用的类有一个私有构造函数。 在此构造函数中,您应该分配相应的值。
或者在声明变量时赋值。

下面的解决方案非常臭,但你在这里:

第 1 步:将现有方法Show重命名为ShowUnsafe

public static MsgDlgResult ShowUnsafe(string message, string title, Buttons buttons, IconImage icon)

第 2 步:MsgBox类中添加一个静态属性MainForm

public static Form MainForm { get; set; }

第 3 步:在应用程序主窗体的构造函数中添加以下行:

MsgBox.MainForm = this;

第 4 步:在类MsgBox中添加一个新方法Show

public static MsgDlgResult Show(string message, string title, Buttons buttons, IconImage icon)
{
    if (!MainForm.IsHandleCreated) return default(MsgDlgResult);
    if (MainForm.InvokeRequired)
    {
        MsgDlgResult result = default(MsgDlgResult);
        Thread.MemoryBarrier();
        MainForm.Invoke((MethodInvoker)delegate { result = ShowSafe(message, title, buttons, icon); });
        Thread.MemoryBarrier();
        return result;
    }
    else
    {
        return ShowSafe(message, title, buttons, icon);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM