Using Task.Factory.StartNew with an action that takes a single int parameter

In the following code, I pass the action declared outside of StartNew, it looks fine.

Action ac = () => { Console.WriteLine("Executing Action in Task 7!");  };
var t7 = Task.Factory.StartNew(ac  );
Task.WaitAny(t7);

But I want to pass the int parameter to the action (I want to declare the action outside of StartNew).

Action<int> ac2 = (n) => 
{
     Console.WriteLine("Executing Action with 1 parameter = {0}", n);              
};
var t9 = Task.Factory.StartNew(  ac2  , 4); //Problem here????

The following code is also good, but I do not want to use Action in this way. I want to define an action outside and call it inside StartNew () as above. How to use ac2 to get the same result as the code below.

var t8 = Task.Factory.StartNew(  (n) => 
{
    Console.WriteLine("Executing Action in Task 8!");
    Console.WriteLine("Param pass {0}", n);

}, 4 );
Task.WaitAny(t8);
+4
source share
4 answers

I don't know why the existing answers are so complicated:

Task.Factory.StartNew(() => ac(4));

That is all that is needed. Just call the function wrapped in lambda. Better to use Task.Run:

Task.Run(() => ac(4));

StartNew object, API, . . .

+4

:

Func<Action<int>, int, Action> createDelegate = (action, arg) =>
{
    return () => action(arg);
};
Task.Factory.StartNew(createDelegate(ac2, 2));
+1

Use Action<object>instead.

Action<object> ac2 = (n) => 
{
     Console.WriteLine("Executing Action with 1 parameter = {0}", n);              
};

var t9 = Task.Factory.StartNew(ac2, 4);

The StartNew () method has no overload for accepting Action<T>or Action<int>for this case. Only allowed to use Action<object>.

0
source

Well, you can use the overload that takes objectto send Tuple<T1, T2>:

        Action<int> ac2 = (n) =>
        {
            Console.WriteLine("Executing Action with 1 parameter = {0}", n);            
        };

        var _data = new Tuple<Action<int>, int>(ac2, 4);

        var t9 = Task.Factory.StartNew((obj) =>
            {
                var data = obj as Tuple<Action<int>, int>;
                data.Item1(data.Item2);
            }, _data);
0
source

Source: https://habr.com/ru/post/1611760/


All Articles