创建具有动作< T,T,... n>的任务.多个参数 [英] Create a Task with an Action<T, T, ... n> multiple parameters

查看:98
本文介绍了创建具有动作< T,T,... n>的任务.多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在包含Action的Task中添加多个参数.我查看了现有的堆栈溢出问题使用Action< T>

I want to add multiple parameter in a Task containing Action. I reviewed the existing stack-overflow question Create a Task with an Action<T>

请协助我如何在Task的Action方法中传递多个参数

Kindly assist me how to pass multiple arguments in a Action method in a Task

Action<string, int> action = (string msg, int count) => 
    { 
        Task.Factory.StartNew(async () => 
            { await LoadAsync(msg, count); }); 
    };


Task task = new Task(action, ....);

操作方法是

public static async Task<string> LoadAsync(string message, int count)
{
    await Task.Run(() => { Thread.Sleep(1500); });
    Console.WriteLine("{0} {1} Exceuted Successfully !", message ?? string.Empty, (count == 0) ? string.Empty : count.ToString());
    return "Finished";
}

请协助我如何创建异步方法的操作以及如何将该操作添加到任务中.

Kindly assist me how to Create a action of an async method and how to add the action into the Task.

推荐答案

只需传递这样的参数即可.

Just pass the parameters like this.

Action<string, int> action = async (msg, count) => await LoadAsync(msg, count);
Task task = new Task(() => action("", 0)); // pass parameters you want

如果您还希望获得返回值

If you want to also get return value

Func<string, int, Task<string>> func = LoadAsync;
Task<string> task = func("", 0); // pass parameters you want

var result = await task; // later in async method

这篇关于创建具有动作&lt; T,T,... n&gt;的任务.多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆