贴一个简单的代码
1:多线程
public class Class1
{
public Class1()
{
Timer timer = new Timer();
timer.Enabled = true;
timer.Interval = 500;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
Console.Read();
}
int n = 0;
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
n++;
System.Threading.Thread t = new System.Threading.Thread(
new System.Threading.ParameterizedThreadStart(newThread));
t.Name = n.ToString();
t.Start(n);
}
void newThread(object n)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("n=" + n + " => i=" + i + "");
System.Threading.Thread.Sleep(1000);
}
Console.WriteLine("线程" + System.Threading.Thread.CurrentThread.Name + "结束");
System.Threading.Thread.CurrentThread.Abort();
System.Threading.Thread.CurrentThread.Join();
}
}
2:委托
public class Class2
{
public Class2()
{
Timer timer = new Timer();
timer.Enabled = true;
timer.Interval = 500;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
Console.Read();
}
int n = 0;
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
n++;
Working(n);
}
private delegate void DelegateReceiveData(int n);
private void CallBackMethod(IAsyncResult ar)
{
try
{
DelegateReceiveData dn = (DelegateReceiveData)ar.AsyncState;
dn.EndInvoke(ar);
}
catch (Exception ex)
{
}
}
private void ReceiveData(int n)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("n=" + n + " => i=" + i + "");
System.Threading.Thread.Sleep(1000);
}
}
protected void Working(int n)
{
DelegateReceiveData dn = new DelegateReceiveData(ReceiveData);
AsyncCallback acb = new AsyncCallback(CallBackMethod);
IAsyncResult iar = dn.BeginInvoke(n, acb, dn);
}
}
结果: