异步委托问题 [英] Asynchronous Delegate Problem

查看:72
本文介绍了异步委托问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨...全部,我想问.我有以下代码:

Hi... All, I want to ask. I have the following code :

internal static class Program
{    
    private static Int32 number = 0;        
    private static Boolean IsComplete = false; 
    private static void Main()
    {        
        Action<Int32> action = arg =>
        {
            for (Int32 i = 0; i < arg; i++)
            {                
                Thread.Sleep(700);
                Console.WriteLine("Result : " + (number += i));
            }                        
        };
 
        action.BeginInvoke(5,
            arg =>
            {                
                Console.WriteLine("action complete, result = {0}", (Int32)arg.AsyncState);                
                IsComplete = true;
            }, 
            number);//if number changed to 10, then "result = 10" printed 
        while (!IsComplete)
        {
            Thread.Sleep(500);
            Console.WriteLine("Main is doing more...");
        }
 
        Console.ReadLine();
    }
}



为什么,当操作完成并且其回调方法总是被调用时,
打印操作完成,结果= 0"(未将数字传递给回调方法).
但是,当我传递10时,它将传递给回调方法?



Why, when action has finished and it''s callback method get called always
printed "action complete, result = 0"(number isn''t passed-in to callback method).
But, when I pass-in 10, then it will passed-in to the call back method ?

推荐答案

它工作正常!

您要做的就是记住发生的事情.

It works fine!

All you have to do is remember when things happen.

Action<int32> action = arg =>
{
    for (Int32 i = 0; i < arg; i++)
    {
        Thread.Sleep(700);
        Console.WriteLine("Result : " + (number += i));
    }
};</int32>

设置委托.什么都没有执行.

Sets up the delegate. Nothing gets executed yet.

action.BeginInvoke(5,
    arg =>
    {
        Console.WriteLine("action complete, result = {0}", (Int32)arg.AsyncState);
        IsComplete = true;
    },
    number);//if number changed to 10, then "result = 10" printed

评估所有参数,然后启动调用.参数的计算结果为:
常数:5
匿名代表.
数字的当前值:0
然后创建线程,并开始.但是,完成时执行的匿名委托已经准备好其参数:0

Evaluates all parameters, then starts the invoke. The parameters evaluate to:
A constant: 5
An anonymous delegate.
The current value of Number: 0
The thread is then created, and starts. But, the anonymous delegate that is executed when it finishes already has it''s parameters ready: 0

while (!IsComplete)
{
    Thread.Sleep(500);
    Console.WriteLine("Main is doing more...");
}

等待所调用的线程完成.

因此,当线程完成时,它将输出零,而不是数字的最终值.
当将数字"更改为"10"时,参数评估为常数值.

为了证明这一点,将数字的初始值设为-6,然后看看会发生什么!

Waits for the invoked thread to complete.

So, when the thread complete, it prints zero, not the final value of number.
When you change "number" to "10" the parameter evaluation is of a constant value.

To prove it, make the initial value of number -6 and see what happens!


这篇关于异步委托问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆