简体   繁体   English

使用C#在线程中调用参数化方法

[英]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? 如何在线程中调用AvtivateFTP()方法并在函数内部传递参数?
  2. Can we call only void type function inside thread? 我们只能在线程内调用void类型函数吗?

I don't know where FTPService comes from but I would expect some member like 我不知道FTPService的来源,但我希望有些会员喜欢

  IAsyncReslt BeginActivate ( ) 

In lack of that, you can use a lambda: 如果没有这个,您可以使用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. 问题2:是的,但是有解决方法,例如在TPL库中,您可以定义一个返回值的Task。

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). 另外,如果您使用的是.NET 4.0,我建议您使用任务并行库(TPL)。 It is much easier to use TPL. 使用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. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM