Question

I have the following code:

private void StartTask<T>(string parameter)
{
    dynamic instance = (T) Activator.CreateInstance(typeof(T), parameter);

    Task.Factory.StartNew(() => instance.DoCompare());
}

This does not work and the "DoCompare()" method does not get called...How do I call a method in a class with parameters in a generic type method?

Class I am initiating:

public class Something {
     private string _parameter;

     public Something(string parameter) {
     _parameter = parameter;
     }

     public void DoCompare(){
      //Do longrunning task
     }
}

EDIT: Removed constraint BaseClass5 because of confusion

EDIT2: I get: A first chance exception of type

'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException'

EDIT3:

This seems to work, the issue seems to be Task.Factory.StartNew:

private void StartTaskAwesomium<T>() where T 
{
    dynamic instance = (T) Activator.CreateInstance(typeof (T), parameter);
    instance.Test();
}
Was it helpful?

Solution 2

The solution was to wrap the creation of the class in the Task itself like this:

private void StartTask<T>(string connectionId) where T : BaseClass5
{          
    Task.Factory.StartNew(() =>
    {
        dynamic instance = (T) Activator.CreateInstance(typeof (T), connectionId);
        instance.DoCompare();
    });
}

OTHER TIPS

In theory your code should work, but it is a "fire-and-forget" pattern, meaning it will be executed sometime, but you have no control over that or can check if it actually was executed or if there was an exception.
Maybe change it to:

private async void StartTask<T>(string parameter) where T : BaseClass5
{
    BaseClass5 instance = (T)Activator.CreateInstance(typeof(T), parameter);
    await Task.Factory.StartNew(() => instance.DoCompare());
}

No need for the dynamic as because of your generic constraint you know that T must be BaseClass5 or based on it.

Or return the task to await (or task.Wait()) it elsewhere:

private Task StartTask<T>(string parameter)
{
    T instance = (T)Activator.CreateInstance(typeof(T), parameter);
    return Task.Factory.StartNew(() => instance.DoCompare());
}
 private void StartTask<T>(string parameter)
{
    dynamic instance = (T) Activator.CreateInstance(typeof(T), parameter);

    Task.Factory.StartNew(() => {instance.DoCompare();});
}

This seems to work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top