using system;
using system.threading;
//不需要构造函数的委托对象
internal sealed class noconstructordelegateclass
{
public static void callbackwithoutnewingadelegateobject()
{
threadpool.queueuserworkitem(someasynctask, 5);
}
private static void someasynctask(object o)
{
console.writeline(o);
}
}
//不需要定义回调方法,生成一个一个静态委托字段,并在调用时实例化
internal sealed class nocallbackmethoddelegateclass
{
public static void callbackwithoutnewingadelegateojbect()
{
threadpool.queueuserworkitem(delegate(object obj) { console.writeline(sm_name + obj); },5);
}
}
//不需要指定回调方法的参数
internal sealed class nocallbackmethodandparametersdelegateclass
{
public static void callbackwithoutnewingadelegateojbect()
{
threadpool.queueuserworkitem(delegate{ console.writeline("test"); }, 5);
}
}
//不需要将局部变量人工封装到类中,即可将它们传给一个回调方法 自动生成辅助类
internal sealed class noenlocalvartoclassdelegateclass
{
public static void usinglocalvariablesinthecallbackcode(int32 numtodo)
{
int32[] squares = new int32[numtodo];
autoresetevent done = new autoresetevent(false);
for (int32 n = 0; n < squares.length; n++)
{
threadpool.queueuserworkitem(delegate(object obj)
{
int32 num = (int32)obj;
squares[num] = num * num;
if (interlocked.decrement(ref numtodo) == 0)
done.set();
}, n);
}
done.waitone();
for (int32 n = 0; n < squares.length; n++)
{
console.writeline("index {0},square = [1]",n,squares[n]);
}
}
}
新闻热点
疑难解答