做接口,前端告诉我,接口等待时间太长了,并且,接口返回值对其没太大意义。于是,为了优化效率,决定采用一个子线程来单独执行真正的写数据的操作,而迅速地返回结果给前端。
核心代码如下:
Log.Loging.Info("Write Objects To Temp GeoGeoDatabase in a Child Thread ...");
//子线程方法定义
var aChildThread = new System.Threading.Thread((param) =>
{
Log.Loging.Info("______Start ChildThread...");
var data = param as Tuple<ProjectInformation, List<object>, List<object>>;
var aDataWriter = new ModelDataWriter() {
TelecomOperator = data.Item1.TelecomOperator,
WorkspacePath =data.Item1.GetProjectDataPath()
};
Log.Loging.Info("Write Reels...");
var reels = aDataWriter.WriteObjects(data.Item2).Cast<object>().ToList();
Log.Loging.Info($"Reel Count = {reels.Count}");
Log.Loging.Info("Write Cores...");
var cores = aDataWriter.WriteObjects(data.Item3).Cast<object>().ToList();
Log.Loging.Info($"Core Count = {cores.Count}");
Log.Loging.Info("Finish ChildThread.______");
});
lock(aChildThread)
{
//启动子线程
aChildThread.Start(
new Tuple<ProjectInformation, List<object>, List<object>>(
projectInfo, lsReel.Cast<object>().ToList(), lsCore.Cast<object>().ToList()));
}
Log.Loging.Info("Add Load Finished.<----------");
在这段代码中,我们将需要传入的参数构造成一个元组Tuple,传递给子线程,然后启动它。我们想要看到的结果应当是,输出最后一句日志信息后,子线程里还在执行写数据的操作。我们看日志,果然验证这一点:
2018-09-03 11:26:31,783 [7] INFO : Write Objects To Temp GeoGeoDatabase in a Child Thread ...
2018-09-03 11:26:31,785 [7] INFO : Add Load Finished.<----------
2018-09-03 11:26:31,797 [15] INFO : ______Start ChildThread...
2018-09-03 11:26:31,797 [15] INFO : Write Reels...
2018-09-03 11:26:34,951 [15] INFO : Reel Count = 48
2018-09-03 11:26:34,951 [15] INFO : Write Cores...
2018-09-03 11:27:13,955 [15] INFO : Core Count = 576
2018-09-03 11:27:13,955 [15] INFO : Finish ChildThread.______
接口测试时发现,原本顺序执行,整个操作需要30~40秒才能完成,改用子线程后,返回结果只需要数毫秒。