简体   繁体   English

在第二个依赖于第一个时执行异步任务

[英]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.

相关问题 C#ForEach循环具有ASync任务和相关的后期ASync任务 - C# ForEach Loop With ASync Tasks & Dependent Post ASync Tasks 执行任务列表时出现问题,每个任务中都有多个异步调用 - Issue when executing a list of tasks, that have multiple async calls inside each one 不同 dbContext 上的异步任务。 说在这种情况下开始了第二次操作 - Async tasks on different dbContexts. Says a second opreration started on this context TPL .ContinueWith在执行许多任务时具有优先级 - TPL .ContinueWith priority when executing a lot of tasks 当任务运行异步方法时,等待所有任务 - Wait for all tasks when tasks run async methods 一个视图中有两个下拉菜单,第二个依赖于第一个选择 - Two dropdowns in one view, second dependent on what is selected on first 2个异步下载请求,但是第二个取决于第一个的结果-如何同步 - 2 asynchronus download requests, but the second is dependent on the result of the first - how to sync 等待异步任务,然后先声明然后等待 - Awaiting async tasks instantly vs declaring first and then awaiting 在Task.WhenAll中执行许多任务时的C#线程 - C# threads when executing many tasks in Task.WhenAll 在递归函数中使用Async / Await时控制任务总数 - Control total number of tasks when using Async/Await in a recursive function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM