博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

C# 线程安全的操作控件

Posted on 2021-03-09 09:44  PHP-张工  阅读(225)  评论(0编辑  收藏  举报

当子线程操作主线程(UI线程)的控件时,可能会造成阻塞或冲突;使用委托就可以避免。

public FrmTelnet()
{
    Control.CheckForIllegalCrossThreadCalls = false;
    InitializeComponent();
}

// 线程安全输出
public delegate void showInfoDelegate(string str);
private void showInfo(string str)
{
    if (txtInfo.InvokeRequired)
    {
        showInfoDelegate la = new showInfoDelegate(showInfo);
        txtInfo.Invoke(la, str);
        return;
    }

    if (txtInfo.TextLength > 100000)
    {
        txtInfo.Text = "";
    }
    txtInfo.AppendText(str.Trim() + System.Environment.NewLine);
}

 简单事件触发备忘

// 消息事件
public delegate void EventInfo(object sender, string info);
public event EventInfo OnEventInfo;

// 触发消息
private void showInfo(string str)
{
    OnEventInfo(this, str);
}

///////// 调用
HttpServer httpServer = new HttpServer();
httpServer.OnEventInfo += eventInfo;

private void eventInfo(object sender, string info)
{
    // 处理
}

 快捷线程创建备忘

Thread ThreadListener = new Thread(() =>
{
    while (true)
    {
        try
        {
        }
        catch
        { }
    }
});
ThreadListener.IsBackground = true;
ThreadListener.Start();