展会信息港展会大全

C#利用子线程刷新主线程
来源:互联网   发布日期:2016-01-26 10:29:43   浏览:2109次  

导读:使用线程操作1、实时显示当前时间2、输入加数和被加数,自动出现结果分析:两个问题解决的方式一致,使用子线程进行时间操作和加法操作,然后刷新主线程的控件显示结果using System; using System Threading; ...

使用线程操作

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

}

}

赞助本站

人工智能实验室

相关热词: 子线程 刷新 主线程 C

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港