I have the following code:
var task = Task.Factory.StartNew(CheckFiles, cancelCheckFile.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
private void CheckFiles()
{
//Do stuff
}
I now want to amend CheckFiles to accept and integer and a BlockingCollection reference
private void CheckFiles(int InputID, BlockingCollection<string> BlockingDataCollection)
{
//Do stuff
}
I can't seem to find a way to Start this task as I did above.
Can you help?
Thanks
This question is related to
c#
.net
.net-4.0
task-parallel-library
class Program
{
static void Main(string[] args)
{
Task.Factory.StartNew(() => MyMethod("param value"));
}
private static void MyMethod(string p)
{
Console.WriteLine(p);
}
}
Try this,
var arg = new { i = 123, j = 456 };
var task = new TaskFactory().StartNew(new Func<dynamic, int>((argument) =>
{
dynamic x = argument.i * argument.j;
return x;
}), arg, CancellationToken.None, TaskCreationOptions.AttachedToParent, TaskScheduler.Default);
task.Wait();
var result = task.Result;
Construct the first parameter as an instance of Action
, e.g.
var inputID = 123;
var col = new BlockingDataCollection();
var task = Task.Factory.StartNew(
() => CheckFiles(inputID, col),
cancelCheckFile.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
For passing a single integer I agree with Reed Copsey's answer. If in the future you are going to pass more complicated constucts I personally like to pass all my variables as an Anonymous Type. It will look something like this:
foreach(int id in myIdsToCheck)
{
Task.Factory.StartNew( (Object obj) =>
{
var data = (dynamic)obj;
CheckFiles(data.id, theBlockingCollection,
cancelCheckFile.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}, new { id = id }); // Parameter value
}
You can learn more about it in my blog
Source: Stackoverflow.com