2015-11-06 42 views
1

我想通過List<items>轉換成AsyncCallback函數LoadHistoryAsync(List<int> Items)result.AsyncStateCallForNewData(IAsyncResult result)爲空爲什麼?AsyncCallback傳遞參數

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

解決問題。

回答

3

documentation

的BeginInvoke方法發起異步調用。它具有與想要異步執行的方法相同的參數,以及另外兩個可選參數。第一個參數是一個AsyncCallback委託,它引用在異步調用完成時要調用的方法。 第二個參數是一個用戶定義的對象,它將信息傳遞到回調方法

你通過一個null,你會得到一個null