[英]Executing async tasks when second dependent on first
I need some help regarding asynchronous programming.我需要一些关于异步编程的帮助。 For simplicity, consider a list of integers 2, 1, 3, 3, 4, 5为简单起见,考虑一个整数列表 2, 1, 3, 3, 4, 5
I have two async tasks.我有两个异步任务。 One to get record and other to create record.一个获取记录,另一个创建记录。 I only want to create a record if the id property does not exist yet.如果 id 属性尚不存在,我只想创建一条记录。
public async Task<Record> GetRecord(int id)
{
var client = new HttpClient();
// build request
// var response = await client.SendAsync(request); // sending to 3rd party vendor
// depending on response, return the Record object or null
}
public async Task<bool> CreateRecord(int id)
{
var client = new HttpClient();
// build request
// var response = await client.SendAsync(request); // sending to 3rd party vendor
// depending on response, return true or false
}
Main program主程序
foreach(var id in IDs)
{
var record = await GetRecord(id); ?? How can I wait here
if (record == null)
await CreateRecord(id)
}
For some reason, this program is creating records with 2, 1, 3, 3, 4, 5. It should not be creating a duplicate record with id 3.出于某种原因,该程序正在创建具有 2、1、3、3、4、5 的记录。它不应该创建具有 id 3 的重复记录。
I also tried the following but it also creates duplicate records我也尝试了以下方法,但它也会创建重复记录
var record = Task.Run( async => await GetRecord(id)).Result
Any help would be greatly appreciated.任何帮助将不胜感激。
Here is a sample I tried showing what you have should work fine.这是我尝试展示的示例,它应该可以正常工作。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TestSync
{
public class Record
{
public int Id { get; set; }
public Record(int id)
{
this.Id = id;
}
}
public class TestClass
{
private List<Record> SavedRecords = new List<Record>();
private List<int> Ids = new List<int>{1, 2, 1, 3, 3, 4, 5, 3, 3, 4, 4, 2, 2};
private Random randome = new Random(8383838);
public async Task Process()
{
foreach (var id in Ids)
{
var record = await GetRecord(id);
if (record == null)
await CreateRecord(id);
}
}
public async Task<Record> GetRecord(int id)
{
await Task.Delay(randome.Next(100, 200));// simulate delay for a HttpClient kind of call
return SavedRecords.FirstOrDefault(i => i.Id == id);
}
public async Task<bool> CreateRecord(int id)
{
await Task.Delay(randome.Next(200, 500));// simulate delay for a HttpClient kind of call
SavedRecords.Add(new Record(id));
return true;
}
public void Print()
{
foreach (var record in SavedRecords)
Console.WriteLine(record.Id);
}
}
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Creating records!");
var t = new TestClass();
await t.Process();
t.Print();
Console.WriteLine("Done creating records!");
Console.ReadKey();
}
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.