异步编程中使用帮助类来实现Thread.Start()的示例

时间:2020-11-28 15:32:20
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{ // 异步调用
// 将需传递给异步执行方法数据及委托传递给帮助器类
ThreadWithState tws = new ThreadWithState(
"This report displays the number {0}.",
,
new ExampleCallback(ResultCallback)
);
Thread t = new Thread(new ThreadStart(tws.ThreadProc));
t.Start();
Console.ReadKey();
} static void ResultCallback(int i)
{
Console.Write("No." + i + "\n");
}
}
} // 包装异步方法的委托
public delegate void ExampleCallback(int lineCount);
// 帮助器类 public class ThreadWithState
{
private string boilerplate;
private int value;
private ExampleCallback callback; public ThreadWithState(string text, int number,
ExampleCallback callbackDelegate) {
boilerplate = text;
value = number;
callback = callbackDelegate;
} public void ThreadProc()
{
Console.WriteLine(boilerplate, value);
// 异步执行完时调用回调
if (callback != null)
callback();
}
}

运行结果:

异步编程中使用帮助类来实现Thread.Start()的示例

摘自:http://www.cnblogs.com/heyuquan/archive/2012/12/16/2820775.html