Web Service 單次回傳大量資料(如 10 萬筆以上)易導致逾時、記憶體飆升、序列化效能差。本文提出**多執行緒分批拉取 + 實體物件反序列化**的流程設計,平衡效能與穩定度。

[WebMethod]
public string GetDataBatch(int batchIndex, int batchSize)
{
// 查詢對應範圍資料,序列化為 XML 回傳
var data = Repository.GetBatch(batchIndex, batchSize);
return SerializeToXml(data);
}
// 簡化邏輯示意
int totalBatches = GetTotalBatches();
var tasks = new List<Task>();
for (int i = 0; i < totalBatches; i++)
{
int batch = i;
tasks.Add(Task.Run(() =>
{
string xml = Client.GetDataBatch(batch, 10000);
var entities = DeserializeXml<List<Entity>>(xml);
ProcessAndSave(entities);
}));
}
Task.WaitAll(tasks.ToArray());
[XmlRoot("Entities")]
public class Entity
{
[XmlElement("Id")] public int Id { get; set; }
[XmlElement("Name")] public string Name { get; set; }
// ...
}
public static List<T> DeserializeXml<T>(string xml)
{
using (var sr = new StringReader(xml))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(sr);
}
}
| 優點 | 缺點/風險 |
|---|---|
| 避免單次大封包傳輸逾時 | 執行緒管理複雜度高 |
| 記憶體壓力分散(逐批處理) | 資料一致性需自行保證(交易、冪等) |
| 可平行化處理提升吞吐 | Web Service 端需支援分頁/游標查詢 |
| 實體物件強型別,開發體驗好 | 錯誤處理、重試、進度追蹤需自建 |
若維護舊版 ASMX Web Service 專案,此方案可作為過渡優化;新專務請直接採用 RESTful API + 分頁/游標 + 非同步串流,架構更清晰、生態工具更豐富。