110,535
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
Task.Factory.StartNew(AutoConnect);//程序启动,创建一个线程
}
private void AutoConnect()
{
while (true)
{
if (po.opcLianJie())
{
BeginInvoke(new Action(() => { richTextBox.Text += "连接成功"; }));
break;
}
else
{
BeginInvoke(new Action(() => { richTextBox.Text += "正在连接中……"; }));
}
Thread.Sleep(5000);
}
}
public class po
{
public static bool opcLianJie()
{
return true;
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Thread pclConnectThread = new Thread(() =>
{
while(true)
{
if (po.opcLianJie())
{
this.Invoke((Action)delegate
{
richTextBox.Text += "连接成功";
});
break;
}
else
{
this.Invoke((Action)delegate
{
richTextBox.Text += "连接失败";
});
}
Thread.Sleep(5000);
}
});
plcConnectThread.Start();
}
在新线程中连接。
private async void MainInterface_Load(object sender,EventArgs e)
{
BLL.XiTongLog.Add("Application Start",null,null);
await Task.Run(new Action(() =>
{
var msg = "";
while (true)
{
try
{
if (po.OPCLianJie())
{
msg = "OPCConnection\r\n";
break;
}
else
msg = "OPCConnecting";
Dispather.Invoke(new Action(() =>
{
richTextBox2.Text += msg;
}));
Task.Delay(5000).Wait();
}
catch { }
}
}));
}