图形设计见前面的文章
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace 文本抄写员程序_方法回调_委托_线程_
{
public partial class Form1 : Form
{
private delegate void WriteTextBox(char ch);
private WriteTextBox writeTextBox;
private delegate void WriteTextBox1Callback(char ch);
private WriteTextBox1Callback wriTextBox1Callback;
private delegate void WriteTextBox2Callback(char ch);
private WriteTextBox2Callback wriTextBox2Callback;
public Form1()
{
InitializeComponent();
wriTextBox1Callback = new WriteTextBox1Callback(WriText1);
wriTextBox2Callback = new WriteTextBox2Callback(WriText2);
}
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
textBox1.Clear();
textBox1.Refresh();
ThreadStart doTask1 = new ThreadStart(DoTsk1);
Thread tsk1Thread = new Thread(doTask1);
tsk1Thread.Start();
}
if (checkBox2.Checked == true)
{
textBox2.Clear();
textBox2.Refresh();
ThreadStart doTask2 = new ThreadStart(DoTsk2);
Thread tsk2Thread = new Thread(doTask2);
tsk2Thread.Start();
}
}
private void DoTsk1()
{
writeTextBox = new WriteTextBox(WriTextBox1);
WriTxt(writeTextBox);
}
private void DoTsk2()
{
writeTextBox = new WriteTextBox(WriTextBox2);
WriTxt(writeTextBox);
}
private void WriTxt(WriteTextBox wMethod)
{
string strdata = textBox3.Text;
for (int i = 0; i < strdata.Length; i++)
{
wMethod(strdata[i]);
DateTime now = DateTime.Now;
while (now.AddSeconds(1) > DateTime.Now)
{ }
}
}
private void WriTextBox1(char ch)
{
textBox1.Invoke(wriTextBox1Callback, ch);
}
private void WriTextBox2(char ch)
{
textBox2.Invoke(wriTextBox2Callback, ch);
}
private void WriText1(char ch)
{
textBox1.AppendText(ch + "\r");
}
private void WriText2(char ch)
{
textBox2.AppendText(ch + "\r");
}
}
}
这个例子显得有点弄不懂了,不明白这个回调的意义在哪里。
以上这五个例子就是C#网络编程的前面的几个小例子,主要是引入委托、回调、线程的概念,虽然有一些概念不是特别理解,希望在今后的学习中能够搞明白吧。
如果有高手看到这个文章,可以评论解释下回调究竟是为什么,明明已经通过多线程实现了并发执行了。。。