I have a class which is responsible for rendering grid records.
ObservableCollection<Dictionary<string, string>> gridData;
ObservableCollection<Dictionary<string, string>> GridData;
{
get
{
return gridData;
}
set
{
this.gridData = value;
NotifyPropertyChanged();
}
}
The above property is binded to the GridControl (Devexpress WPF).
Below is async method which is responsible for rendering the data from back end service.
public async void RefresRecords()
{
await GetRecords();
}
private async Task GetRecords()
{
int offset = 0;
int limit = 50;
do
{
var dummyData = await GetRangeRecord(offset, limit);
GridData.Add(dummyData);
offset += limit;
} while (GridData.Count() < 1000);
}
private Task<Dictionary<string, string>> GetRangeRecord(int offset, int limit)
{
// This method does processing and returns records from offset to limit
return new Task<Dictionary<string, string>>();
}
From the back end service there can be huge amount of data but i want to show only top 1000 records.
The records would be fetched in chunk of 50 records per call. As the property is binded, UI will be refreshed simultaneously.
Now consider the use case as below:-
Step 1:- Call comes for asyn method "RefresRecords". Assume there are 1000 records fetched from backend service. So this method will loop for 20 time and will display 50 records per service call.
Step2:- While Step1 is in process as it is async call, another call comes for the same async method "RefreshRecords".
Result:- After Step 2, the Grid would be loaded with data from the fetched data of Step2 as well as some portion of Step1 as the same property is getting modified in the two subsequent asyn method call.
Question:- What is the best way to stop the Step1 completely when there is a fresh call for the same method.
You could use cancellation tokens for your async methods. And when the GetRecords() method is called do a GridData.Clear().
This is a very simple demonstration but hope it helps.
public static List<int> List = new List<int>();
public static async Task AddToList(CancellationToken cancellation)
{
List.Clear();
for (var i = 0; i < 100 && !cancellation.IsCancellationRequested; i++)
{
await Task.Delay(100, cancellation);
List.Add(i);
}
}
public static async Task MainAsync(CancellationToken cancellation)
{
await AddToList(cancellation);
}
private static void Main(string[] args)
{
var cts = new CancellationTokenSource();
Task.Run(() => MainAsync(cts.Token), cts.Token);
Thread.Sleep(1000);
cts.Cancel();
cts = new CancellationTokenSource();
Task.Run(() => MainAsync(cts.Token), cts.Token).Wait(cts.Token);
Console.WriteLine(List.Count);
Console.Read();
}
Hope this helps
look here for more http://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx