如何启动一个任务,需要一个参数,并返回一个值? [英] How to start a task that takes a parameter and returns a value?

查看:143
本文介绍了如何启动一个任务,需要一个参数,并返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图推出在C#中的任务,既需要一个参数和返回值,但我似乎无法得到语法正确。

I'm trying to launch a task in C# that both takes a parameter and returns a value, but I can't seem to get the syntax right.

下面是因为我已经得到了接近:这里的,预计将返回一个int的任务。我在我的lambda,我也显示它采取一个参数,O:

Here's as close as I have gotten: here's a task that is expected to return an int. I'm my lambda, I'm also showing it taking a single parameter, o:

Task<int> task1 = Task.Factory.StartNew<int>((o) => { return 2 ; }, 3);
Console.WriteLine(task1.Result);  // prints 2

以上线路工程(它返回的2硬codeD值,但你可以看到它在做什么用的参数0,使其失去作用。如果我做了什么与参数0,这样的:

The above line works (it returns a hardcoded value of 2, but you can see it's doing nothing with the parameter o, making it useless. If I do something with the parameter o, like this:

Task<int> task1 = Task.Factory.StartNew<int>((o) => { return (2 * o) ; }, 3);

我得到一个语法消息,委托System.Func不带1个参数。

I get a syntax message that Delegate 'System.Func' does not take 1 arguments.

这是如何实现两件事任何帮助(参数传递和获取的值)从一个任务将是巨大的!

Any help on how to achieve both things (pass a parameter and retrieve a value) from a task would be great!

推荐答案

0 是对象的状态,并在你的情况,是要传递的值,或3.您可以将其转换为一个 INT

o is the object state, and in your case, is the value you are passing in, or 3. You can cast it to an int.

Task<int> task = Task.Factory.StartNew<int>(o => {
    return 2 * (int)o;
}, 3);

Console.WriteLine(task.Result); // prints 6

请参阅MSDN对 TaskFactory 的文档。<一个HREF =htt​​p://msdn.microsoft.com/en-us/library/dd321394相对=nofollow> StartNew 其中规定:

See msdn's documentation on TaskFactory.StartNew which states:

状态

类型:System.Object

Type: System.Object

要使用的功能委托包含数据的对象。

An object containing data to be used by the function delegate.

这篇关于如何启动一个任务,需要一个参数,并返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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