Salesforce | Fetch more than 2000 records using REST asynchronously in C#

| By Webner

Salesforce gives us a limit of 2000 records to fetch from it using REST calls. But sometimes we need to get all the records from Salesforce. In Salesforce, there is a limit of API calls. By default, it gives 15,000 for a sandbox. Making salesforce call, again and again, consumes lots of API calls. One needs to purchase a license to extend this limit. Then why not optimize the code?

ForceClient library (automatically comes with Salesforce.Force NuGet package) provides a method that makes an asynchronous call and does not have the restriction of fetching only 2000 records. It can fetch all the records in one go.

See below code :

public static async Task<List> getallrecords(ForceClient client)
     var list = new List();
        string qry = "select Id from CustomObject";

        var results = await client.QueryAsync(qry);
        var totalSize = results.TotalSize;
        var nextRecordsUrl = results.NextRecordsUrl;

        if (!string.IsNullOrEmpty(nextRecordsUrl))
        System.Diagnostics.Debug.WriteLine("next record url.");
        while (true)
               var asynlist = await 
               totalSize = asynlist.TotalSize;
               System.Diagnostics.Debug.WriteLine("Next " + totalSize+ 

                if (string.IsNullOrEmpty(asynlist.NextRecordsUrl)) 

                nextRecordsUrl = asynlist.NextRecordsUrl;
            	System.Diagnostics.Debug.WriteLine("total  = " + totalSize);
        	catch (Exception ex)
        	return list ;

You can find the more details regarding the ForceClient library methods at the link “”.

Leave a Reply

Your email address will not be published. Required fields are marked *