Kelly Cline
Kelly Cline

Reputation: 2246

Task Factory StartNew Generic

There is a Task.Factory.StartNew(Action<Object> action, Object state) method. This looks generic. But, if my "action" is

protected void Edit(MyType myType) { }

why can't I have

MyType x = something;
Task.Factory.StartNew(Edit, x);

I get:

Argument 1: cannot convert from 'method group' to 'System.Action'

I can get it to work by adding another method,

protected void Edit(object myType) { Edit((MyType)myType); }

or I can write

Task.Factory.StartNew(() => Edit(x));

but I feel like I'm missing something that should allow me to do it the first way...

Upvotes: 2

Views: 2345

Answers (2)

trousyt
trousyt

Reputation: 356

The method signature for Task.Factory.StartNew is asking for a single-parameter Action<>, so simply create an Action<> instance and use that in your call:

protected void Edit( Object myType ){ ... }

MyType x = something;
Action<Object> action = new Action<Object>(Edit);
Task.Factory.StartNew( action, x );

or

Task.Factory.StartNew(new Action<Object>(Edit), x);

You may be able to inline this using lambdas as well (which you noted):

Task.Factory.StartNew( () => Edit(x) );

Upvotes: -1

Lee
Lee

Reputation: 144126

The Edit method group is not convertible to Action<object>. You could do

Action<MyType> act = Edit;

but there is no conversion between Action<MyType> and Action<object>. If there were you could do

Action<object> act = Edit;
act("abc");

Upvotes: 2

Related Questions