Pankaj
Pankaj

Reputation: 4505

Call Parameterized method in thread using c#

Hello All I want to call a function in thread which is taking some parameter like

FTPService FtpOj = new FTPService();
 FtpOj.AvtivateFTP(item, ObjFTP, AppHelper.DoEventLog, AppHelper.DoErrorLog, AppHelper.EventMessage, strLableXmlPath, AppHelper.emailfrom);
  1. How can i call AvtivateFTP() method in thread and pass parameter inside function?
  2. Can we call only void type function inside thread?

Upvotes: 1

Views: 1492

Answers (2)

Vlad Bezden
Vlad Bezden

Reputation: 89547

Answer your second question. You can call method that returns any value. Here is example of it:

static void Main()
{
  Func<string, int> method = Work;
  IAsyncResult cookie = method.BeginInvoke ("test", null, null);
  //
  // ... here's where we can do other work in parallel...
  //
  int result = method.EndInvoke (cookie);
  Console.WriteLine ("String length is: " + result);
}

static int Work (string s) { return s.Length; }

Also if you are using .NET 4.0 I would recommend to use Task Parallel Library (TPL). It is much easier to use TPL.

Another suggesting is since you have many parameters that you pass to the function, wrap them in one object and pass that object to your async method.

Hope this will help.

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273229

I don't know where FTPService comes from but I would expect some member like

  IAsyncReslt BeginActivate ( ) 

In lack of that, you can use a lambda:

  ThreadPool.QueueUserWorkItem( () => FtpOj.AvtivateFTP(item, ...) );

And to question 2: Yes, but there are workarounds, for example in the TPL library you can define a Task returning a value.

Upvotes: 1

Related Questions