C#子线程刷新主线程 C#利用子线程刷新主线程分享教程

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C#子线程刷新主线程 C#利用子线程刷新主线程分享教程

  2021-03-19 我要评论
想了解C#利用子线程刷新主线程分享教程的相关内容吗,在本文为您仔细讲解C#子线程刷新主线程的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C#,子线程,刷新,主线程,下面大家一起来学习吧。
要求:如下图,使用线程操作
1、实时显示当前时间
2、输入加数和被加数,自动出现结果
 
分析:两个问题解决的方式一致,使用子线程进行时间操作和加法操作,然后刷新主线程的控件显示结果
复制代码 代码如下:

using System;
using System.Threading;
using System.Windows.Forms;
namespace WinThread
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
/// <summary>
/// 初始化
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void frmMain_Load(object sender, EventArgs e)
{
// 控件初始化
this.txtOne.Text = "0";
this.txtSecond.Text = "0";
// 显示时间操作
Thread showTimeThread = new Thread(new ThreadStart(GetTime));
showTimeThread.IsBackground = true;
showTimeThread.Start();
// 加法操作
Thread addThread = new Thread(new ThreadStart(Add));
addThread.IsBackground = true;
addThread.Start();
}
#region 显示时间操作
/// <summary>
/// 取得实时时间
/// </summary>
private void GetTime()
{
try
{
while (true)
{
string currentTime = string.Format("{0}.{1}", DateTime.Now.ToLongTimeString(), DateTime.Now.Millisecond);
ShowTime(currentTime);
Application.DoEvents();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
// 定义显示时间操作委托,用于回调显示时间方法
delegate void ShowTimeCallBack(string str);
/// <summary>
/// 实时显示时间
/// </summary>
/// <param name="str"></param>
private void ShowTime(string str)
{
if (this.txtCurrentTime.InvokeRequired)
{
ShowTimeCallBack showTimeCallBack = new ShowTimeCallBack(ShowTime);
this.Invoke(showTimeCallBack, new object[] { str });
}
else
{
this.txtCurrentTime.Text = str;
}
}
#endregion
#region 加法操作
/// <summary>
/// 加法操作
/// </summary>
private void Add()
{
try
{
while (true)
{
int i = Convert.ToInt32(this.txtOne.Text.Trim());
int j = Convert.ToInt32(this.txtSecond.Text.Trim());
ShowResult((i + j).ToString());
Application.DoEvents();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
// 定义加法操作委托,用于回调加法操作方法
delegate void ShowResultCallBack(string result);
/// <summary>
/// 显示结果
/// </summary>
/// <param name="result"></param>
private void ShowResult(string result)
{
if (this.txtResult.InvokeRequired)
{
// 写法1
//ShowResultCallBack showResultCallBack = new ShowResultCallBack(ShowResult);
//this.Invoke(showResultCallBack, new object[] { result });
// 写法2
//使用委托来赋值
this.txtResult.Invoke(
//委托方法
new ShowResultCallBack(ShowResult),
new object[] { result });
}
else
{
this.txtResult.Text = result;
}
}
#endregion
}
}

是不是很简单呢?

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们