use*_*675 41 c# asynchronous execution
我听说异步执行有四种模式.
"异步委托执行有四种模式:轮询,等待完成,完成通知和"消防和忘记".
当我有以下代码时:
class AsynchronousDemo
{
public static int numberofFeets = 0;
public delegate long StatisticalData();
static void Main()
{
StatisticalData data = ClimbSmallHill;
IAsyncResult ar = data.BeginInvoke(null, null);
while (!ar.IsCompleted)
{
Console.WriteLine("...Climbing yet to be completed.....");
Thread.Sleep(200);
}
Console.WriteLine("..Climbing is completed...");
Console.WriteLine("... Time Taken for climbing ....{0}",
data.EndInvoke(ar).ToString()+"..Seconds");
Console.ReadKey(true);
}
static long ClimbSmallHill()
{
var sw = Stopwatch.StartNew();
while (numberofFeets <= 10000)
{
numberofFeets = numberofFeets + 100;
Thread.Sleep(10);
}
sw.Stop();
return sw.ElapsedMilliseconds;
}
}
Run Code Online (Sandbox Code Playgroud)
1)上述代码实现的模式是什么?
2)你能解释一下代码,我该如何实现其余的代码?
Bob*_*Bob 94
你有什么轮询模式.在这种模式中,你不断问"我们还在吗?" 该while循环是做阻塞.所述Thread.Sleep防止吃起来的CPU周期的过程.
等待完成是"我会打电话给你"的方法.
IAsyncResult ar = data.BeginInvoke(null, null);
//wait until processing is done with WaitOne
//you can do other actions before this if needed
ar.AsyncWaitHandle.WaitOne();
Console.WriteLine("..Climbing is completed...");
Run Code Online (Sandbox Code Playgroud)
因此,一旦WaitOne被召唤,你就会阻止攀爬完成.您可以在阻止之前执行其他任务.
完成通知后,您说"你打电话给我,我不会打电话给你."
IAsyncResult ar = data.BeginInvoke(Callback, null);
//Automatically gets called after climbing is complete because we specified this
//in the call to BeginInvoke
public static void Callback(IAsyncResult result) {
Console.WriteLine("..Climbing is completed...");
}
Run Code Online (Sandbox Code Playgroud)
这里没有阻止因为Callback会被通知.
而且会发生火灾和遗忘
data.BeginInvoke(null, null);
//don't care about result
Run Code Online (Sandbox Code Playgroud)
这里也没有阻挡,因为攀爬完成时你并不在意.顾名思义,你会忘记它.你说的是"不要打电话给我,我不会打电话给你,但是,不要打电话给我."
| 归档时间: |
|
| 查看次数: |
39477 次 |
| 最近记录: |