我有两个问题:
ThreadPool函数而不将对象作为参数(要将一个函数插入到threadPool,它需要是返回一个参数-object的函数)例如,我想插入这个函数:double foo(int a,double b,string c)?wait在池中执行线程(比如连接)?发布于 2011-12-21 09:33:33
对于第一部分,最简单的方法可能是:
根据您的描述假设一种方法:
public double foo(int a, double b, string c)
{
...
}您可以在线程池上使用以下命令对此进行排队:
ThreadPool.QueueUserWorkItem(o => foo(a, b, c));对于第二部分,虽然不能等待ThreadPool线程,但可以在线程池上异步调用方法,并等待它们的完成(这似乎是您正在寻找的)。
同样,假设Foo方法的定义如下所示。
为Foo定义代表:
private delegate double FooDelegate(int a, double b, string c);然后使用FooDelegate的BeginInvoke/EndInvoke方法异步调用Foo:
// Create a delegate to Foo
FooDelegate fooDelegate = Foo;
// Start executing Foo asynchronously with arguments a, b and c.
var asyncResult = fooDelegate.BeginInvoke(a, b, c, null, null);
// You can then wait on the completion of Foo using the AsyncWaitHandle property of asyncResult
if (!asyncResult.CompletedSynchronously)
{
// Wait until Foo completes
asyncResult.AsyncWaitHandle.WaitOne();
}
// Finally, the return value can be retrieved using:
var result = fooDelegate.EndInvoke(asyncResult);以解决意见中提出的问题。如果您希望并行执行多个函数调用,并在继续之前等待它们全部返回,则可以使用:
// Create a delegate to Foo
FooDelegate fooDelegate = Foo;
var asyncResults = new List<IAsyncResult>();
// Start multiple calls to Foo() in parallel. The loop can be adjusted as required (while, for, foreach).
while (...)
{
// Start executing Foo asynchronously with arguments a, b and c.
// Collect the async results in a list for later
asyncResults.Add(fooDelegate.BeginInvoke(a, b, c, null, null));
}
// List to collect the result of each invocation
var results = new List<double>();
// Wait for completion of all of the asynchronous invocations
foreach (var asyncResult in asyncResults)
{
if (!asyncResult.CompletedSynchronously)
{
asyncResult.AsyncWaitHandle.WaitOne();
}
// Collect the result of the invocation (results will appear in the list in the same order that the invocation was begun above.
results.Add(fooDelegate.EndInvoke(asyncResult));
}
// At this point, all of the asynchronous invocations have returned, and the result of each invocation is stored in the results list.发布于 2011-12-21 09:06:28
这两个问题的答案都是否定的,虽然如果将输入的args打包到状态对象中并编写机制以提供等待功能和获取工作项方法的结果,则可以获得相同的结果。
http://smartthreadpool.codeplex.com/做你想做的一切;
public static void Main(string[] args)
{
var threadPool = new SmartThreadPool();
IWorkItemResult<int> workItem=null;
SmartThreadPool.WaitAll(new IWaitableResult[ ]{workItem = threadPool.QueueWorkItem(new Amib.Threading.Func<int, int, int>(Add), 1, 2)});
Console.WriteLine(workItem.Result);
Console.ReadLine();
}
public static int Add(int a, int b)
{
return a+b;
}发布于 2011-12-21 09:13:58
关于您的第一个问题,创建一个调用foo的正确签名的新方法(返回一个对象参数)。如果您需要将特定的参数传递给foo,然后创建一个类或结构,或者使用Tuple<int, double, double>并将其转换为object将其传递给ThreadMethod,然后返回到Tuple,将参数传递给foo。
void ThreadMethod(object obj)
{
var args = (Tuple<int, double, double>)obj;
foo(args.Item1, args.Item2, args.Item3);
}Re.第二个问题,你必须自己创建线程,这样你才能保持一个Thread对象来加入。
https://stackoverflow.com/questions/8587275
复制相似问题