This question has already been answered:

I am writing a scheduler for different tasks of working with the database, it is loading, unloading, data processing. all actions are implemented as separate classes and inherited from an abstract class and must implement the required Run () method

The tasks themselves are stored in the database table. One of the fields indicates the class name of the Run () method of which you want to run on a schedule. accordingly, at startup, you need to determine which class instance to create

private void TimerTask(object Obj) { IsRuning = true; SetNextStartTask(); switch (Metod) { case "ExportXML0": { Task task = Task.Factory.StartNew(() => { ExportData export = new ExportXML0(Id); export.Run(); }); if (task.IsCompleted) { task.Dispose(); } break; } case "ExportUniversalToTXT": { Task task = Task.Factory.StartNew(() => { ExportData export = new ExportUniversalToTXT(Id); export.Run(); }); if (task.IsCompleted) { task.Dispose(); } break; } } IsRuning = false; } 

Now there are relatively few classes, about 30. When there are 100+, then this method will look scary. How can you simplify this choice?

In some languages, for example, SQL or Caché Basic, you can write some text and execute it, how beautiful it is to do it in C #

Reported as a duplicate by Grundy , AK , 0xdb , user192664, aleksandr barakin participants on 6 Oct '18 at 17:40 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • one
    Keyword - reflection - Andrew

1 answer 1

Use reflection

 Task task = Task.Factory.StartNew(() => { ExportData export = (ExportData)Activator.CreateInstance( assemblyName, Metod, new object[] {Id} ); export.Run(); }); if (task.IsCompleted) { task.Dispose(); } 
  • And what in this example is id ? - NewView
  • @NewView is the same id as the author of the question in ExportData export = new ExportXML0(Id); - Bulson
  • Aah, I get it, thanks. - NewView