Vicky
Vicky

Reputation: 45

how to call method from new thread

am working to avoid the time out issues from web application and web service.

so what am trying to do is whatever the logic that am doing in web service method currently am trying to call that logic from new thread and after initiating new thread i want to return some value to web application so connection will end with out getting timeout issue and new thread will do its process on the service side.can we do like this???

and how can i call method from new thread??

am trying to do code something like below..

[WebMethod]
public bool callingmethod(int num1,int num2)
{ 
   employee emp=new employee();
   thread t=new thread(emp.method(num1,num2));
   t.start();
   return true;
}

public class employee
{
   public void method(int a ,int b)
   {
      logic...
   }
}

please advice me..i have been searching every where to get appropriate logic but everything is way complicated..

Upvotes: 0

Views: 138

Answers (3)

Matt
Matt

Reputation: 2682

Just because you're spawning a new thread doesn't mean that you can't have exceptions that need to be handled. If you're using .NET 4 or higher, I'd do this with a task since it's better to use a ThreadPool thread in this case:

public bool callingmethod(int num1, int num2)
{
    Task.Factory.StartNew(() =>
    {
        employee emp = new employee();
        emp.method(num1, num2);
    }).ContinueWith(x => Console.WriteLine(x.Exception.ToString()), TaskContinuationOptions.OnlyOnFaulted);
    return true;
}

If you'd prefer doing this manually or are using < .NET 4, try

public bool callingmethod(int num1, int num2)
{        
    ThreadPool.QueueUserWorkItem(x =>
    {
        try
        {
            employee emp = new employee();
            emp.method(num1, num2);
        }
        catch (Exception ex)
        {
            // Log exception
        }
    });
    return true;
}

Note that in both cases these are on background threads, since if you quit your application you don't want the thread to keep running.

Upvotes: 0

Erik
Erik

Reputation: 12868

public bool MainMethod(int a, int b)
{
  var employee = new Employee();

  ThreadPool.QueueUserWorkItem((argument) => { employee.DoWorkAsync(a, b); });

  return true;
}

public class Employee
{
  public void DoWorkAsync(int a, int b)
  {
    // Do some work on a background thread.
  }
}

Upvotes: 0

JaredPar
JaredPar

Reputation: 755397

To do this you can pass a lambda expression to the Thread constructor that represents the code to execute when the thread begins running

Thread t= new Thread(() => emp.method(num1,num2));

Upvotes: 1

Related Questions