创建具有动作的任务<T> [英] Create a Task with an Action&lt;T&gt;

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

问题描述

不知何故,我觉得我缺少一些基本的东西.这是我的问题.

我正在尝试创建一个 System.Threading.Tasks.Task 实例来执行接受某种类型参数的操作.我以为我可以做类似的事情

void DoWork(MyClass obj) {}//接受'MyClass'类型参数的我的动作MyClass obj = new MyClass();动作行动 = DoWork;//指向方法的动作任务 task = new Task(action,obj);//当我调用 Start 时,将使用 'obj' 作为参数执行 'DoWork' 的任务.

显然这不能编译.看来我只能对任务使用 Action 而不是 Action,然后在我的方法中将对象"转换为 T.>

我怎样才能最有效、最高效地实现我想要的?

解决方案

你也可以直接使用:

MyClass obj = new MyClass();任务 task = Task.Run(() => DoWork(obj));

I somehow feel I am missing something basic. Here's my problem.

I am trying to create a System.Threading.Tasks.Task instance to execute an action that accepts a parameter of a certain type. I thought I could do something like

void DoWork(MyClass obj) {} //My action that accepts a parameter of type 'MyClass'

MyClass obj = new MyClass(); 
Action<MyClass> action = DoWork; //action that points to the method
Task task = new Task(action,obj); //task that would execute 'DoWork' with 'obj' as the parameter when I call Start.

Obviously this does not compile. It seems I can only use an Action<object> and not an Action<T> for a task and then cast the 'object' to T inside my method.

How can I achieve what I want most effectively and efficiently?

解决方案

You also can use directly:

MyClass obj = new MyClass();
Task task = Task.Run(() => DoWork(obj));

这篇关于创建具有动作的任务<T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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