locked
Can task entry point method be an instance method or it can be only a static method? RRS feed

  • Question

  • Hi!

    Can task entry point method be an instance method or it can be only a static method?

    Friday, July 5, 2013 11:58 AM

Answers

  • I am not sure what you mean by entry point but a TPL task represents an asynchronous operation that will run the the delegate that you pass to it at some point in time. The delegate encapsulates the code that the task will execute and can be expressed as a named delegate, an anonymous method, or a lambda expression.

    A task is not in any way restricted to only run static methods. For example, you can start a new task to run an instance method as follows:

    private IService service;
    
            private void StartTask()
            {
                Task<int>.Run(() => { return _service.SomeMethodReturningAnInteger(); });
    ...
            }
    

    • Marked as answer by TownSparrow Friday, July 5, 2013 1:33 PM
    Friday, July 5, 2013 12:26 PM

All replies

  • I am not sure what you mean by entry point but a TPL task represents an asynchronous operation that will run the the delegate that you pass to it at some point in time. The delegate encapsulates the code that the task will execute and can be expressed as a named delegate, an anonymous method, or a lambda expression.

    A task is not in any way restricted to only run static methods. For example, you can start a new task to run an instance method as follows:

    private IService service;
    
            private void StartTask()
            {
                Task<int>.Run(() => { return _service.SomeMethodReturningAnInteger(); });
    ...
            }
    

    • Marked as answer by TownSparrow Friday, July 5, 2013 1:33 PM
    Friday, July 5, 2013 12:26 PM
  • A Task can execute any delegate and you can create a delegate from any static method or any instance method on a specific instance. That's because delegates are more than just function pointers (they are basically a function pointer together with an instance reference).
    Friday, July 5, 2013 12:44 PM
  • Thank you very much for both answers. Both of them are very useful.

    Eugene.

    Friday, July 5, 2013 1:36 PM