0

I have a method public void foo(){} which in turn calls another method public void fooBL(){} which is in the BusinessLogic layer. fooBL() then calls another method fooDAL() which is in the DataAccessLayer. I want to call foo() asynchronously on a button click event. I'm using .NET4.0.

pravprab
  • 2,301
  • 3
  • 26
  • 43
Niar
  • 532
  • 2
  • 11
  • 23

3 Answers3

2

It depends on what your goal is.

The simplest way to call foo asynchronous is:

Task t = new Task.Factory.StartNew(foo);
TheJoeIaut
  • 1,522
  • 2
  • 26
  • 59
1

You can use thread to run method asynchronously. Below is an example:

Thread t = new Thread(new ThreadStart(foo));              
t.Start();

I hope it helps you. :)

Hitesh
  • 3,508
  • 1
  • 18
  • 24
1

You can wrap anything in Task.Run to run it via the default scheduler (the ThreadPool):

Task.Run(() => {
    yourMethodCallHere();
});

You should avoid the use of StartNew if you are unaware of how it works. You could introduce potential bugs as it captures the currently executing TaskScheduler instance and you will no doubt hit "cross-thread" exceptions when dealing with UI elements (or other, much more subtle bugs).

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138