using System;
using System.Threading;
using System.Threading.Tasks;
namespace TaskExample
{
class c4
{
static void Main()
{
var t1 = new Task<Tuple<int, int> > ( Fun2,
Tuple.Create< int, int >( 16, 5 ) );
t1.Start();
Console.WriteLine( t1.Result );
t1.Wait();
Console.WriteLine( "result from task: {0} {1}", t1.Result.Item1, t1.Result.Item2 );
string str = "Hello";
var t2 = new Task<Tuple<int>>( Fun1, str );
t2.Start();
t2.Wait();
Console.WriteLine( "result of t2 is {0}.", t2.Result.Item1 );
}
static Tuple< int, int > Fun2( object division )
{
Tuple< int, int > div = (Tuple<int, int > )division;
int result = div.Item1 / div.Item2;
int reminder = div.Item1 % div.Item2;
Console.WriteLine( "task creates a result..." );
return Tuple.Create< int, int >( result, reminder );
}
static Tuple<int> Fun1( object msg )
{
Console.WriteLine( msg );
return Tuple.Create<int>(1);
}
}
}
运行结果:
task creates a result...
(3, 1)
result from task: 3 1
Hello
result of t2 is 1.
t1:传入2个参数,返回2个参数。
t2:传入1个参数,返回1个参数。返回值是一个时,也可以参考t1的方法。
不论是参数还是返回值,都可以是多个,具体都看Tuple。