0
点赞
收藏
分享

微信扫一扫

C# 关于通讯观察线程(1) -- 开启通讯线程

龙驹书房 2024-06-26 阅读 30
c#javajvm

通讯观察线程是个有意思,又是非常实用的功能。

具体怎么实现呢,我们来看看主要过程的伪代码。对于高手这也许很简单,但是要用好也是需要实践到通讯的流程正确,同时应对好网络故障等。

先在合适的地方启动观察线程:

/// <summary>
/// 通讯观察线程,每3秒观察一次
/// </summary>
System.Timers.Timer communicationobserve_timer = new System.Timers.Timer(1000 * 3);

communicationobserve_timer.Elapsed += new System.Timers.ElapsedEventHandler(CommunicationObser);

communicationobserve_timer.Enabled = true;

这样通讯线程开起来了。

/// <summary>
/// 通讯状态观察
/// </summary>
private void CommunicationObser(object sender, ElapsedEventArgs e)
{
    try
    {
        communicationobserve_timer.Enabled = false;
        var resultList = GetOrder.GetMesDispatchInfo();
        if (resultList != null)
        {
            ShowMsg($"\n"); //以下是业务代码
            if (resultList.Count != -1 && resultList.Data != null)
            {
                LogHelper.Info(JsonConvert.SerializeObject(resultList));   
                #region //以下是业务代码
                //....
                //....
                //....
 
                #endregion 
            }            
        }
        else
        {
            ShowMsg($"发生错误:返回为空,如果是网络断线请稍后重试");
        }
    }
    catch (Exception ex)
    {
        ShowMsg($"发生错误:返回通讯方法错误!请联系管理员");
        LogHelper.Error($"观察线程异常:{ex.Message}", ex);
    }
    finally
    {
        communicationobserve_timer.Enabled = true;
    }
}

上面是通讯的内容,我就滤过业务代码,因为重点其实是后面,断线重连。断线重连在下一节介绍。C# 关于通讯观察线程(2) -- 断线重连-CSDN博客

举报

相关推荐

0 条评论