C# 多线程示例
Posted 杨咩咩plus
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 多线程示例相关的知识,希望对你有一定的参考价值。
using System;
using System.Windows.Forms;
using System.Threading;
namespace 多线程
{
delegate void SetValueCallback(int value);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(Foo));
t.Start();
}
private void Foo()
{
for (int i = 1; i <= 100; i++)
{
Thread.Sleep(100);//间隔1秒继续下面的程序
SetProcessBarValue(i);//设置progressBar1的值
SetLabelValue(i);//设置label1的值
}
}
private void SetLabelValue(int value)
{
if (this.label1.InvokeRequired)
{
SetValueCallback d = new SetValueCallback(SetLabelValue);
this.Invoke(d, new object[] { value });
}
else
{
this.label1.Text = value.ToString() + \'%\';
}
}
private void SetProcessBarValue(int value)
{
// InvokeRequired required compares the thread ID of the calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.progressBar1.InvokeRequired)
{
SetValueCallback d = new SetValueCallback(SetProcessBarValue);
this.Invoke(d, new object[] { value });
}
else
{
this.progressBar1.Value = value;
}
}
private void button2_Click(object sender, EventArgs e)
{
Thread th = new Thread(new ThreadStart(Fuu));
th.Start();
}
private void Fuu()
{
int m = 0;
for (int i = 1; i <= 100; i++)
{
Thread.Sleep(50);//间隔0.05秒继续下面的程序
m = m + i;
}
MessageBox.Show(m.ToString());
}
}
}
以上是关于C# 多线程示例的主要内容,如果未能解决你的问题,请参考以下文章
C# 之 多线程 -- 任务概念以及使用示例 ( Task | TaskCompletionSource | Async | Await )