我有一个系统只是去服务器并检索一些文本,以最大化我想要立即发送许多请求的性能。代码如下所示:
var okButton.Text = TextSystem.Get("ok",language);
然而,它允许从代码中的任何地方进行TextSystem调用,并将其与其他代码混合。因此,如果开发人员在使用系统之前必须预先加载系统,那么开发人员使用系统会有点困难。
所以,如果有可能
,我会更加聪明我想要这样的事情:
var okButton1.Text = TextSystem.Get("ok1",language); // Start thread X and buffer the
// request
var okButton2.Text = TextSystem.Get("ok2",language); // Add ok2 to the request buffer
FinanceCall(); // Execute this call, oh 10ms has passed since thread X started
// send the request with ok1 and ok2 to remote server.
// The server has respond, change the value for okButton1.Text and okButton2.Text.
var okButton3.Text = TextSystem.Get("ok3",language); // Start thread Y and do the same..
此代码将在ASP.NET中执行,因此我关心的是在呈现页面之前设置okButton1.Text。我在考虑是否有一些异步/等待方法可行,但我想就如何解决这个问题提供一些意见。
答案 0 :(得分:1)
不确定为什么需要聚合请求,但我建议让开发人员每次添加请求放入队列或列表然后在需要时处理它们:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
internal class Program
{
private static void Main(string[] args)
{
var r1 = new Request {Callback = r => Console.WriteLine(r), Parm1 = "ok1", Parm2 = "language"};
TextSystem.QueueRequest(r1);
var r2 = new Request {Callback = r => Console.WriteLine(r), Parm1 = "ok2", Parm2 = "language"};
TextSystem.QueueRequest(r2);
var r3 = new Request {Callback = r => Console.WriteLine(r), Parm1 = "ok3", Parm2 = "language"};
TextSystem.QueueRequest(r3);
var r4 = new Request {Callback = r => Console.WriteLine(r), Parm1 = "ok4", Parm2 = "language"};
TextSystem.QueueRequest(r4);
TextSystem.Flush();
Console.Read();
}
}
public static class TextSystem
{
private static readonly List<Request> requests = new List<Request>();
static TextSystem()
{
requests = new List<Request>();
}
public static void QueueRequest(Request request)
{
requests.Add(request);
}
public async static void Flush()
{
List<Tuple<Request, string>> results = await Task.Run(() =>
{
var list = new List<Tuple<Request, string>>();
//process each request
foreach (Request request in requests)
{
//Get data, process or whatever
list.Add(new Tuple<Request, string>(request, request.Parm1));
}
return list;
});
//Callback on same thread as the request was initiated on
foreach (var result in results)
{
result.Item1.Callback(result.Item2);
}
}
}
public class Request
{
public Action<string> Callback { get; set; }
public string Parm1 { get; set; }
public string Parm2 { get; set; }
}
}