0

I need to create and pass a action/delegate of a method at runtime to TaskFactory.Satrtnew method. In general I would do the following when i know the method to use.

public void SomeService(CancellationToken cToken)
{   }

var tasks = new Task[] {
     Task.Factory.StartNew(() => SomeService(new CancellationToken())
};

In my case, when I to do this at runtime, where my method names comes from configuration file. The method exists but it would be assigned to task at runtime. I tried something like

var conn = bll.daService.DbConnection;
var currentType = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType; 
var method = currentType.GetMethod("SomeService");

Action<CancellationToken> action = (Action<CancellationToken>)
   Delegate.CreateDelegate(typeof(Action<CancellationToken>),currentType,method);

Task.Factory.StartNew(action);

And also something like.

delegate void ServiceDelegate(CancellationToken cToken);

ServiceDelegate serDel = (ServiceDelegate) 
    Delegate.CreateDelegate(currentType,method);

Action ac = serDel(new CancellationToken());

Task.Factory.StartNew(ac);

None of them are working.It throws different kind of errors and exceptions.

EDIT: The following line throws exception "Type must derive from Delegate"

ServiceDelegate serDel = (ServiceDelegate)
    Delegate.CreateDelegate(currentType,method)
jnovo
  • 5,659
  • 2
  • 38
  • 56
Mady
  • 459
  • 1
  • 11
  • 26

0 Answers0