【问题标题】:passing a method to Thread which have multiple arguments in C#将方法传递给 C# 中具有多个参数的 Thread
【发布时间】:2012-05-19 01:49:18
【问题描述】:

我想在一个线程中执行一个方法。该方法有多个参数并期望返回值。有人可以帮忙吗?

【问题讨论】:

标签: c#


【解决方案1】:
Thread thread = new Thread(() => 
       {
          var result = YourMethod(param1, param2);
          // process result here (does not invoked on your main thread)
       });

如果您需要将结果返回到主线程,请考虑改用 Task (C# 4):

var task = new Task<ReturnValueType>(() => YourMethod(param1, param2));
task.Start();

// later you can get value by calling task.Result;

或者使用以前版本的 C#

Func<Param1Type, Param2Type, ReturnValueType> func = YourMethod;            
IAsyncResult ar = func.BeginInvoke(param1, param2, null, null);
ar.AsyncWaitHandle.WaitOne();
var result = func.EndInvoke(ar);

【讨论】:

  • @Servy 在这种情况下只是避免了
【解决方案2】:
Func<string, int, bool> func = SomeMethod;
AsyncCallback callback = ar => { bool retValue = func.EndInvoke(ar); DoSomethingWithTheValue(retValue };
func.BeginInvoke("hello", 42, callback, null);


...

bool SomeMethod(string param1, int param2) { ... }

【讨论】:

  • 在这种情况下,DoSomethingWithTheValue 不会在主线程上执行。只需调用Thread thread = new Thread(() =&gt; DoSomething(YourMethod(param1, param2))) 即可获得相同的结果
猜你喜欢
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-20
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多