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]);
}
}
}
新聞熱點
疑難解答