最近一直在搞多线程的东西,但是总是迷迷糊糊的。前几天有个哥们给我讲了一个方法,感觉不错。特此分享下!解决方案界面如下:
![]()
其中Form1.cs为主窗体,Program.cs为Main方法,ThreadHelpClass.cs为线程帮助类
Form1主窗体的界面如下:
![]()
点击button1运行效果如下:
![]()
具体代码如下:(按我写的顺序贴给大家)
![]()
首先是在Program类中声明两个委托,Program的源码如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Demo1
{
//操作数据的委托
public delegate void ThreadDelegate(Hashtable ht);
//操作前台的委托
public delegate void ThreadInvokeDelegate(Hashtable htInvoke);
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
然后在线程帮助类(ThreadHelpClass.cs),具体实现代码:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Demo1
{
//操作帮助类
public class ThreadHelpClass
{
private ThreadDelegate threadDel;//创建委托对象
//构造函数(参数为委托对象)
public ThreadHelpClass(ThreadDelegate ht)
{ threadDel = ht; }
//实现方法(主要就是一个 +1 操作)
public void run()
{
Hashtable ht = new Hashtable();//声明Hashtable
ht["Total"] = 10;//设置滚动条的总长度
for (int i = 0; i < 10; i++)
{
ht["single"] = i + 1;//对滚动条的每个单位进行+1操作
threadDel(ht);//最后添加到委托实例中
Thread.Sleep(1000);//挂起1s钟
}
}
}
}
最后Form1.cs主窗体的主要代码如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Demo1
{
public partial class Form1 : Form
{
/// <summary>
/// 加载主窗体界面
/// </summary>
public Form1()
{InitializeComponent();}
/// <summary>
/// 启动操作按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//设置滚动条最小值为0
this.progressBar1.Minimum = 0;
//初始化线程帮助类实例,参数为委托对象
ThreadHelpClass thc = new ThreadHelpClass(new ThreadDelegate(ThreadFun));
//初始化线程,调用帮助类里的run方法
Thread th = new Thread(new ThreadStart(thc.run));
th.Start();//开启线程
}
/// <summary>
/// 初始化线程帮助类调用的方法
/// </summary>
/// <param name="ht"></param>
public void ThreadFun(Hashtable ht)
{
try
{
//调用Invoke方法获取数据
this.Invoke(new ThreadInvokeDelegate(ThreadInvokeFun), new object[] { ht });
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 用控件赋值方法
/// </summary>
/// <param name="ht"></param>
public void ThreadInvokeFun(Hashtable ht)
{
this.progressBar1.Maximum = Convert.ToInt32(ht["Total"]);
this.progressBar1.Value = Convert.ToInt32(ht["single"]);
}
}
}
好了,利用上面的代码就可以实现功能了!
这个主要是帮助初学者或者和我一样不怎么懂多线程的人的,希望你看了后有所收获!