Create a task with action <T>
I somehow feel that I am missing something basic. Here is my problem.
I am trying to create an instance of System.Threading.Tasks.Task to perform an action that takes a parameter of a specific type. I thought I could do something like
void DoWork(MyClass obj) {} //My action that accepts a parameter of type 'MyClass' MyClass obj = new MyClass(); Action<MyClass> action = DoWork; //action that points to the method Task task = new Task(action,obj); //task that would execute 'DoWork' with 'obj' as the parameter when I call Start. Obviously, this does not compile. It seems I can use an Action<object> rather than an Action<T> for the task, and then overlay the “object” on T inside my method.
How can I achieve what I want most efficiently and effectively?
you can use
Action<Object> action = o => DoWork((MyClass)o); Task task = new Task(action, obj); If you use .NET 4.0 or higher, you can use Contravariance to achieve your goal without introducing a new delegate
// INCORRECT Code, casts InvalidCastException at runtime Action action = DoWork; Task task = new Task ((Action) action, obj);
EDIT:
Thank you for @svick for pointing out that the second option is incorrect: I was too busy figuring out whether the action is coincident or contravariant (actually it is contravariant, I was right at least) that I need covariance in in this case.
Contravariance means you can do
Action<object> action1 = someAction; Action<SubClass> action2 = action1; without explicit casting.