gpt4 book ai didi

c# - AsyncCallback 传递参数

转载 作者:太空宇宙 更新时间:2023-11-03 23:26:52 35 4
gpt4 key购买 nike

我想通过List<items>进入AsyncCallback在函数中 LoadHistoryAsync(List<int> Items)但是result.AsyncStateCallForNewData(IAsyncResult result)为什么为空?

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);

已解决的问题。

最佳答案

来自documentation :

The BeginInvoke method initiates the asynchronous call. It has the same parameters as the method that you want to execute asynchronously, plus two additional optional parameters. The first parameter is an AsyncCallback delegate that references a method to be called when the asynchronous call completes. The second parameter is a user-defined object that passes information into the callback method.

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

关于c# - AsyncCallback 传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33563366/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com