【问题标题】:AsyncCallback pass parameterAsyncCallback 传递参数
【发布时间】:2015-11-06 17:35:55
【问题描述】:

我想在函数LoadHistoryAsync(List<int> Items) 中将List<items> 传递给AsyncCallback,但CallForNewData(IAsyncResult result) 中的result.AsyncState 为空,为什么?

namespace ConsoleApplication3
{
class Program
{
    static void Main(string[] args)
    {
        List<int> Items = new List<int>();
        Data D = new Data();
        D.LoadHistoryAsync(Items);
        //D.LoadNewPointsAsync(Items);
        Console.ReadKey();
    }
}
public class Data
{
    public void LoadHistoryAsync(List<int> Items)
    {
        Action<List<int>> GetHistoryInformation = new Action<List<int>>(GetHistory);
        //IAsyncResult History = GetHistoryInformation.BeginInvoke(Items, null, null);
        IAsyncResult History = GetHistoryInformation.BeginInvoke(Items, new AsyncCallback(CallForNewData), null);
    }

    public void GetHistory(List<int> Items)
    {
        Random rnd = new Random();
        System.Threading.Thread.Sleep(rnd.Next(1,5000));
        Items.Add(1);
        Console.WriteLine("HistoryLoaded");
    }
    public void CallForNewData(IAsyncResult result)
    {
       Console.WriteLine("Result: {0}",result.AsyncState);
    }

    public void LoadNewPointsAsync(List<int> Items)
    {
        //while(!History.IsCompleted)
        //{
            System.Threading.Thread.Sleep(100);
        //}
        Action<List<int>> GetPointsInformation = new Action<List<int>>(GetPoints);
        IAsyncResult NewPoints = GetPointsInformation.BeginInvoke(Items, null, null);
    }

    public void GetPoints(List<int> Items)
    {
        Random rnd = new Random();
        System.Threading.Thread.Sleep(rnd.Next(1, 5000));
        Items.Add(2);
        Console.WriteLine("New data loaded");
    }
}
}

编辑:

IAsyncResult History = GetHistoryInformation.BeginInvoke(Items, new AsyncCallback(CallForNewData), Items);

问题已解决。

【问题讨论】:

    标签: c# asynccallback


    【解决方案1】:

    来自documentation

    BeginInvoke 方法启动异步调用。它具有与您要异步执行的方法相同的参数,以及两个额外的可选参数。第一个参数是一个 AsyncCallback 委托,它引用异步调用完成时要调用的方法。 第二个参数是用户自定义对象,将信息传递给回调方法

    你传递一个null,你得到一个null

    【讨论】:

      猜你喜欢
      • 2012-02-29
      • 2011-08-03
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多