Reputation: 2097
I was just trying to learn threading and I was wondering can we pass parameter and use return values while creating threads .i am creating Thread using Task.Factory.StartNew .I am just trying to figure something without anonymous function.
Can somebody help me in better understanding.Should I use delegate here. Below is the code that i want to work with(just for learning purpose I do not want to use anonymous and lambda) .Is it possible?
using System;
using System.Threading.Tasks;
public class Example
{
private static int printMessage(int c)
{
int ctr = c;
for (ctr = 0; ctr <= 1000000; ctr++)
{ }
return ctr;
}
public static void Main()
{
Task t = Task.Factory.StartNew(new Action(printMessage));
t.Start();
t.Wait();
Console.WriteLine("The sum is: " + t.Result);
Console.ReadLine();
}
}
Upvotes: 1
Views: 824
Reputation: 156918
Yeah, sure. You have to use Func<object, T>
and pass in the value for c
as an object
. Since the task has a result, you should use Task<int>
instead of Task
:
private static int printMessage(object c)
{
int ctr = (int)c;
for (ctr = 0; ctr <= 1000000; ctr++)
{ }
return ctr;
}
public static void Main()
{
Task<int> t = Task.Factory.StartNew(new Func<object, int>(printMessage), 1);
t.Start();
t.Wait();
Console.WriteLine("The sum is: " + t.Result);
Console.ReadLine();
}
Upvotes: 1