首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AsyncCallback通参数

AsyncCallback通参数
EN

Stack Overflow用户
提问于 2015-11-06 09:23:46
回答 1查看 1.9K关注 0票数 1

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

代码语言:javascript
复制
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");
    }
}
}

编辑:

代码语言:javascript
复制
IAsyncResult History = GetHistoryInformation.BeginInvoke(Items, new AsyncCallback(CallForNewData), Items);

问题解决了。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-06 09:35:55

来自文档

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

你通过一个null,你得到一个null

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33563366

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档