简体   繁体   English

如何使用REST API优化请求JSON的C#代码

[英]How to optimize c# code requesting JSON using REST api

I have to make ac# application which uses REST api to fetch JIRA issues. 我必须制作一个使用REST API来获取JIRA问题的ac#应用程序。 After I run the tool I am getting the correct output but it is taking a lot of time to display the output. 运行该工具后,我将获得正确的输出,但是要花费很多时间才能显示输出。 Below is the part of code which is taking the maximum time 以下是占用最大时间的代码部分

var client =new WebClient();

foreach(dynamic i in jira_keys)
{
 issue_id=i.key;
 string rest_api_url="some valid url"+issue_id;
 var jira_response=client.DownloadString(rest_api_url);

 //rest of the processing
}

jira_keys is a JArray. jira_keys是一个JArray。 After this there is processing part of the JSON in the for each loop. 之后,在每个循环中处理JSON的一部分。 This is taking a lot of time as the number of jira_keys increase. 随着jira_keys数量的增加,这会花费很多时间。 I cannot apply multi-threading to this since there are shared variable issues. 由于存在共享变量问题,因此我无法对此应用多线程。 So please someone suggest some way to optimise this. 因此,请有人提出一些优化方法。

If the issues are tied to a specific project or some other grouping, you can instead search for issues with a JQL string. 如果问题与特定项目或其他组相关,则可以搜索带有JQL字符串的问题。 This way you get them in bulk and paginated. 这样,您可以批量获取它们并进行分页。

https://docs.atlassian.com/jira/REST/cloud/#api/2/search-search https://docs.atlassian.com/jira/REST/cloud/#api/2/search-search

Also, like cubrr said in his comment, async calls should work fine if you want to make api calls with multiple threads. 另外,就像cubrr在他的评论中所说,如果要使用多个线程进行api调用,异步调用应该可以正常工作。 Awaiting the call will block until the shared resources are ready. 等待呼叫将阻塞,直到共享资源准备就绪为止。

(Would have posted as a comment if I had enough rep) (如果我有足够的代表,会发表评论)

Here is an example of how you can fetch the responses from JIRA asynchronously. 这是如何从JIRA异步获取响应的示例。

var taskList = new List<Task<string>>();
foreach (dynamic i in jira_keys)
{
    issue_id = i.key;
    string rest_api_url = "some valid url" + issue_id;
    var jiraDownloadTask = Task.Factory.StartNew(() => client.DownloadString(rest_api_url));
    taskList.Add(jiraDownloadTask);
}
Task.WaitAll(taskList.ToArray());

//access the results
foreach(var task in taskList)
{
    Console.WriteLine(task.Result);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM