2 回答

TA貢獻1864條經驗 獲得超6個贊
獲取值后立即返回該值如何。不允許流程向前移動并打破循環。
using (var Contexts = instContextfactory.GetContextList())
{
foreach(var context in Contexts.GetContextList())
{
// how do I make all the calls and return data from the first call that finds data and continue with the further process.(don't care about other calls if any single call finds data.
var result = await context.Insurance.GetInsuranceByANI(ani);
if(result.Any())
{
return result.First();
}
}
}

TA貢獻1828條經驗 獲得超3個贊
為了簡單起見,您應該首先改回您的GetInsuranceByANI方法以再次同步。稍后我們將生成任務以異步調用它。
public IEnumerable<Insurance> GetInsuranceByANI(string ani)
{
using (ITransaction transaction = Session.Value.BeginTransaction())
{
transaction.Rollback();
IDbCommand command = new SqlCommand();
command.Connection = Session.Value.Connection;
transaction.Enlist(command);
string storedProcName = "spGetInsurance";
command.CommandText = storedProcName;
command.Parameters.Add(new SqlParameter("@ANI", SqlDbType.Char, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, ani));
var rdr = command.ExecuteReader();
return MapInsurance(rdr);
}
}
現在來實現異步搜索所有數據庫的方法。我們將為每個數據庫創建一個任務,在線程池線程中運行。這是值得商榷的,但我們正在努力讓事情變得簡單。我們還實例化 a CancellationTokenSource,并將其傳遞Token給所有Task.Run方法。這只會確保在我們得到結果后,不會再啟動更多任務。如果線程池中的可用線程多于要搜索的數據庫,則所有任務將立即開始,取消令牌實際上不會取消任何內容。換句話說,無論如何,所有啟動的查詢都將完成。這顯然是一種資源浪費,但我們再次努力讓事情變得簡單。
啟動任務后,我們將進入一個等待下一個任務完成的循環(使用方法Task.WhenAny)。如果找到結果,我們取消令牌并返回結果。如果未找到結果,我們將繼續循環以獲得下一個結果。如果所有任務都完成但我們仍然沒有結果,我們將返回 null。
async Task<IEnumerable<Insurance>> SearchAllByANI(string ani)
{
var tasks = new HashSet<Task<IEnumerable<Insurance>>>();
var cts = new CancellationTokenSource();
using (var Contexts = instContextfactory.GetContextList())
{
foreach (var context in Contexts.GetContextList())
{
tasks.Add(Task.Run(() =>
{
return context.Insurance.GetInsuranceByANI(ani);
}, cts.Token));
}
}
while (tasks.Count > 0)
{
var task = await Task.WhenAny(tasks);
var result = await task;
if (result != null && result.Any())
{
cts.Cancel();
return result;
}
tasks.Remove(task);
}
return null;
}
使用示例:
IEnumerable<Insurance> result = await SearchAllByANI("12345");
if (result == null)
{
// Nothing fould
}
else
{
// Do something with result
}
- 2 回答
- 0 關注
- 170 瀏覽
添加回答
舉報