Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)qq
published in(发表于) 2014/7/11 9:28:09
C#教程:线程应用实例

C#教程:线程应用实例

线程应用实例

如果在一个软件开发项目中,需要将数据脱机,如保存在文件过程中,然后再将文件中的数据进行处理,这时就需要实时的监控一个目录中的文件数量以判断文件中的数据是否被处理。下面将通过一个例子说明线程在程序中的应用。在这个例子中要建立一个永久线程,这个永久线程将每隔一段时间就遍历指定的一个文件夹,并计算出被监视的文件夹及其子文件夹中文件的数量。

程序开发步骤如下所示。

(1)在VS2005中新建一个Windows应用程序项目,并命名为ThreadMonitorFile。

(2)打开Windows窗体设计器将窗体重命名为FrmMain,并将Text属性设为“FrmMain”。在FrmMain窗体添加一个TextBox控件、一个Button控件和一个Lable控件。将Lable的Text属性设为“监视的路径:”,Button的Text属性设为“开始监视”。具体界面设计如图1所示。



图1 线程实例主窗体界面设计图

(3)添加一个Windows窗体,并命名为frmThread。在frmThread窗体上添加3个Lable控件。将Lable1控件的Text属性设为“监视的路径:”,Lable2的Text属性设为“正在查询监视路径下文件数量,请等待。”,Lable3的Text属性设为“文件的数量:”。具体界面设计如图2所示。



图2 线程实例frmThread窗体界面设计图

(4)双击FrmMain窗体的【开始监视】按钮,给窗体添加一个静态成员,代码如下:

public static string path;

在按钮的双击事件中调用frmThread窗体。FrmMain窗体调用frmThread窗体的代码如下:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace ThreadMonitorFile

{

public partial class FrmMain : Form

{

public static string path;

public FrmMain()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

FrmMain.path = this.textBox1.Text;

frmThread frm = new frmThread();

frm.Show();

}

}

}

(5)双击frmThread窗体,为窗体添加两个成员变量和一个委托。代码如下:

private int j = 0;

private Thread t = null;

delegate void SetTextCallback(string text);

同时为窗体添加GetAllFiles()方法遍历文件夹中文件方法,Forver()方法永久线程调用的方法,SetText()方法Windows窗体控件线程安全调用方法。具体代码如下:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.IO;

using System.Threading;

namespace ThreadMonitorFile

{

public partial class frmThread : Form

{

private int j = 0;

private Thread t = null;

delegate void SetTextCallback(string text);

public frmThread()

{

InitializeComponent();

}

private void frmThread_Load(object sender, EventArgs e)

{

label3.Text = FrmMain.path;

t = new Thread(new ThreadStart(Forver));

t.Start();

}

public int GetAllFiles(DirectoryInfo dir)

{

FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();


If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759