You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将VB.NET中含InvokeRequired的Log方法转换为C#代码?

VB.NET日志方法转C#实现

原VB.NET代码:

Private Sub Log(Message As String)

    Try

        If txtLog.InvokeRequired Then

            txtLog.Invoke(Sub()
                              Log(Message)
                          End Sub)
        Else
            txtLog.AppendText(Message & Environment.NewLine)
        End If

    Catch ex As Exception

    End Try

End Sub

转换后的C#代码:

private void Log(string Message)
{
    try
    {
        if (txtLog.InvokeRequired)
        {
            txtLog.Invoke(new Action(() =>
            {
                Log(Message);
            }));
        }
        else
        {
            txtLog.AppendText(Message + Environment.NewLine);
        }
    }
    catch (Exception ex)
    {
    }
}

转换关键点说明:

  • VB.NET的Sub()匿名方法对应C#中的Action委托
  • 字符串拼接运算符&替换为C#标准的+
  • 控件跨线程调用的核心逻辑保持一致,通过InvokeRequired判断线程状态后,调用Invoke执行委托完成日志追加操作

内容的提问来源于stack exchange,提问作者Timothy Waters

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 00:15:36