1. C#開發C/S程式,有時需要幾個端,如伺服器端,管理端,用戶端等等, 端與端之間是不同線程或者進程,這就涉及跨線程調用的問題,
使用委託或者非同步線程是必不可少的,這裡是一個簡單的委託線程,即通過委託調用另外一個線程;
2. 有圖有真相:
3. 源碼:
View Code using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace ThreadControlExample
{
public partial class Form1 : Form
{
Thread thread1;
Thread thread2;
delegate void AppendStringDelegate(string str);
AppendStringDelegate appendStringDelegate;
public Form1()
{
InitializeComponent();
appendStringDelegate = new AppendStringDelegate(AppendString);
}
private void AppendString(string str)
{
richTextBox1.Text += str;
}
private void Method1()
{
while (true)
{
Thread.Sleep(100); //線程1休眠100毫秒
richTextBox1.Invoke(appendStringDelegate, "a");
}
}
private void Method2()
{
while (true)
{
Thread.Sleep(100); //線程2休眠100毫秒
richTextBox1.Invoke(appendStringDelegate, "b");
}
}
private void buttonStart_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
thread1 = new Thread(new ThreadStart(Method1));
thread2 = new Thread(new ThreadStart(Method2));
thread1.Start();
thread2.Start();
}
private void buttonStop_Click(object sender, EventArgs e)
{
thread1.Abort();
thread1.Join();
thread2.Abort();
thread2.Join();
MessageBox.Show("線程1、2終止成功");
}
}
}