做个记号,先。后面再总结。
环境:.NET fx4.7 .NET standard 2
场景:winform 操控射频读写器,控件回调显示交互结果,指令下发后回叫是委托,那线程间通信就是个问题,。
网上看了一个侦听端口的
(源地址找不见了,好像是supersocket的一个例子)
using System;
using System.Collections.Generic;
namespace SSClient
{
public class LogHelper
{
public delegate void LogEvent(string msg);
public static List<string> allLines = new List<string>();
public static int displayLength = 0;
private static LogEvent OnLog { get; set; }
/// <summary>
/// winform使用后台线程写显示Log
/// </summary>
public static void SetOnLog(LogEvent e)
{
OnLog = e;
//每100毫秒重新渲染到界面
var timer = new System.Timers.Timer(100);
timer.Elapsed += new System.Timers.ElapsedEventHandler((s, x) =>
{
try
{
int count = allLines.Count;
if (displayLength == count)
return;
//最多保留Log行数
if (allLines.Count > 5000)
allLines.RemoveRange(0, 20);
displayLength = allLines.Count;
OnLog(string.Join("\r\n", allLines));
}
catch { }
});
timer.Enabled = true;
timer.Start();
}
/// <summary>
/// 普通的文件记录日志
/// </summary>
/// <param name="info"></param>
public static void WriteLog(string info)
{
if (OnLog != null)
{
allLines.Add(string.Join(" ", DateTime.Now.ToString("HH:mm:ss"), info));
}
}
/// <summary>
/// 错误日志
/// </summary>
/// <param name="info"></param>
/// <param name="se"></param>
public static void WriteLog(string info, Exception se)
{
if (OnLog != null)
{
allLines.Add(info);
}
}
}
}
定义一个处理回显的
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
private void Form1_Load(object sender, EventArgs e)
{
LogHelper.SetOnLog(new LogHelper.LogEvent((m) =>
{
txtAll.Text = txtAll.Text = (m + "\r\n");
txtAll.Select(txtAll.TextLength, 0);
txtAll.ScrollToCaret();
}));
}
CheckForIllegalCrossThreadCalls = false;
有这句,有没有LogHelper没差。也是个不安操作,有什么不安,先搁一边再试一下另一个方法InvokeRequired...
//CheckForIllegalCrossThreadCalls = false;
private delegate void WriteLogUnSafe(TextBox textboxLog, string msg);
public void Log(TextBox textboxLog, string msg)
{
//LogHelper.WriteLog(msg);
if (this.InvokeRequired)
{
WriteLogUnSafe InvokeWriteLog = new WriteLogUnSafe(Log);
this.Invoke(InvokeWriteLog, new object[] { textboxLog, msg });
}
else
{
txtContainer.AppendText(msg + "\r\n");
}
}
工作的很好,怎么解释,容某想想。。
想到一个处理方式,收到信息后存在公共变量中,让变量的变化触发委托,一搜就找到一段,
public delegate void delegateHandler();
public class my
{
public int i=0;
public delegateHandler myhandle;
public int changeI
{
get{return i;}
set{
i=value;
myhandle();
}
}
}
public class otherclass
{
public my o;
public otherclass()
{ o=new my();
}
pulic void init()
{
o.myhandle+=new delegateHandler(howtodeal);
}
public void howtodeal()
{
//你自己的处理程序
}
}
下周试试。