无法获得TaskCompletionSource的结果

时间:2018-08-02 07:06:01

标签: c# async-await task taskcompletionsource

您好,我遇到以下问题:

我想执行类似于交易的操作。我想在收到外部触发器后执行许多async操作。因此,我使用的TaskCompletionSource是在表示触发器的方法中设置的:TriggerTransaction

当我按下特定的控制台键时,会在线程池的Main中调用此触发方法。

当我按下A关键字后,TriggerTransaction被执行,而TaskCompletionSource -s被设置。但主线程仍不计算两个等待任务的总和。

     class Program
                {
                    public static Task<Task<int>> TransactionOperation1()
                    {
                        TaskCompletionSource<Task<int>> tcs = new TaskCompletionSource<Task<int>>();
                        tasks.Add(tcs);
                        Task<Task<int>> result = tcs.Task;
                        return result;
                    }
                    public static Task<Task<int>> TransactionOperation2()
                    {
                        TaskCompletionSource<Task<int>> tcs = new TaskCompletionSource<Task<int>>();
                        tasks.Add(tcs);
                        Task<Task<int>> result = tcs.Task;
                        return result;
                    }

                    public static async Task<int> ExecuteTransactionOnDB()
                    {
                        await Task.Delay(1000);
                        return 5;
                    }

                    public static async Task TriggerTransaction()
                    {
                        int value = await ExecuteTransactionOnDB();
                        foreach (var item in tasks)
                        {
                            item.SetResult(value);
                        }
                    }
                    public static List<dynamic> tasks = new List<dynamic>();

                    static async Task Main(string[] args)
                    {
                        Task<Task<int>> a = TransactionOperation1();
                        Task<Task<int>> b = TransactionOperation2();
                        Task.Run(async() =>
                        {
                            while (Console.ReadKey().Key != ConsoleKey.A) ;
                            await TriggerTransaction();
                        });
                        if (!File.Exists("D:\\data.txt"))
                        {
                            File.Create("D:\\data.txt");
                        }
                        using(FileStream stream=new FileStream("data.txt",FileMode.Append,FileAccess.Write))
                        {
                        int sum=await await a + await await b;//thread wont pass this line when tasks are set.
                        ReadOnlyMemory<byte> bytes = Encoding.UTF8.GetBytes(sum);

                            stream.Write(bytes.ToArray());
                        }
                        Console.WriteLine(await await a + await await b);

                    }
                }
        }

PS 如果您想知道为什么我确实使用List<dynamic>来存储TaskCompletionSource-s,那是因为TransactionOperations的返回类型会有所不同。其中有些会返回int,其他String .. Bool .. etc。

为了更好地理解,我制作了一个架构- 如您所见,有:
-我要在其中存储TCS-es的列表
-某些调用仅在设置了外部触发器(执行事务)之后才完成
正如您在Calls中所看到的,它们都有不同的返回类型。
enter image description here

2 个答案:

答案 0 :(得分:1)

您为什么需要Task<Task<int>>?只需Task<int>就足够了,因此TaskCompletionSource<int>就足够了。而且,您还摆脱了笨拙的await await ...,在您的情况下也不需要这样做。

请注意,我还向Close()返回的流中添加了File.Create()

这是该程序的有效版本:

class Program
{
    public static Task<int> TransactionOperation1()
    {
        TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
        tasks.Add(tcs);
        return tcs.Task;
    }
    public static Task<int> TransactionOperation2()
    {
        TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
        tasks.Add(tcs);
        return tcs.Task;
    }
    public static async Task<int> ExecuteTransactionOnDB()
    {
        await Task.Delay(1000);
        return 5;
    }
    public static async Task TriggerTransaction()
    {
        int value = await ExecuteTransactionOnDB();
        foreach (var item in tasks)
        {
            item.SetResult(value);
        }
    }

    public static List<dynamic> tasks = new List<dynamic>();

    static async Task Main(string[] args)
    {
        Task<int> a = TransactionOperation1();
        Task<int> b = TransactionOperation2();
        Task input = Task.Run(async () => {
            while (Console.ReadKey().Key != ConsoleKey.A);
            await TriggerTransaction();
        });
        if (!File.Exists("C:\\temp\\data.txt"))
        {
            File.Create("C:\\temp\\data.txt").Close();
        }
        using (FileStream stream = new FileStream("C:\\temp\\data.txt", FileMode.Append, FileAccess.Write))
        {
            int sum = await a + await b; // now it works ok
            var bytes = Encoding.UTF8.GetBytes(sum.ToString());
            stream.Write(bytes);
        }

        Console.WriteLine(await a + await b);
    }
}

答案 1 :(得分:1)

通过执行使用Task创建的TaskCompletionSource,检出代码的修改后的版本,可以产生预期的结果。我也将代码设为泛型,因此您无需使用dynamic类型并在编译时定义数据类型

static async Task Main(string[] args)
{
    var a = Program<int>.TransactionOperation1();
    var b = Program<int>.TransactionOperation2();
    await Task.Run(async() =>
    {
    Console.ReadLine();
    await Program<int>.TriggerTransaction(5);
    });

    if (!File.Exists("D:\\data.txt"))
    {
    File.Create("D:\\data.txt");
    }

    using (FileStream stream = new FileStream("D:\\data.txt", FileMode.Append, FileAccess.Write))
    {
        int sum = await a + await b;//thread wont pass this line when tasks are set.        
        var bytes = Encoding.UTF8.GetBytes(sum.ToString());     
        stream.Write(bytes, 0, bytes.Length);
    }

    Console.WriteLine(await a + await b);
}

class Program<T>
{
    public static Task<T> TransactionOperation1()
    {
        var tcs = new TaskCompletionSource<T>();
        tasks.Add(tcs);
        return tcs.Task;
    }

    public static Task<T> TransactionOperation2()
    {
        var tcs = new TaskCompletionSource<T>();
        tasks.Add(tcs);
        return tcs.Task;
    }

    public static async Task<T> ExecuteTransactionOnDB(T t)
    {
        return await Task.FromResult(t);
    }

    public static async Task TriggerTransaction(T t)
    {
        T value = await ExecuteTransactionOnDB(t);

        foreach (var item in tasks)
        {
            item.SetResult(value);
        }
    }

    public static List<TaskCompletionSource<T>> tasks = new List<TaskCompletionSource<T>>();

}

以下是重要的修改:

  1. List<dynamic>替换为List<TaskCompletionSource<T>>
  2. TransactionOperation1/2的返回类型为Task<T>,这是使用TaskCompletionSource<T>创建的任务
  3. Task.Run添加了一个额外的等待时间,它可以在内部执行TriggerTransaction,尽管您可以替换以下代码:

     await Task.Run(async() =>
     {
       Console.ReadLine();
       await Program<int>.TriggerTransaction(5);
     });
    

    与     await Program<int>.TriggerTransaction(5);

现在它会按预期产生结果,它将两个整数相加。诸如删除Task.Delay这样的其他一些小的更改不是必需的

编辑1-使用Task.WhenAll

static async Task Main(string[] args)
{
    var a = Program.TransactionOperation1(5);
    var b = Program.TransactionOperation1(5);

    Console.ReadLine();

    var taskResults  = await Task.WhenAll(a,b);


    dynamic finalResult = 0;

    foreach(var t in taskResults)
        finalResult += t;


    if (!File.Exists("D:\\data.txt"))
    {
        File.Create("D:\\data.txt");
    }

    using (FileStream stream = new FileStream("D:\\data.txt", FileMode.Append, FileAccess.Write))
    {
        var bytes = Encoding.UTF8.GetBytes(finalResult.ToString());
        stream.Write(bytes, 0, bytes.Length);
    }

    Console.WriteLine(finalResult);
}

class Program
{
    public static Task<dynamic> TransactionOperation1(dynamic val)
    {
        return Task<dynamic>.Run(() => val);
    }

    public static Task<dynamic> TransactionOperation2(dynamic val)
    {
        return Task<dynamic>.Run(() => val);
    }

}