C#中的ThreadPool

aha*_*ron 1 c# threadpool

我有两个问题:

  1. 有没有办法插入一个ThreadPool没有得到对象作为参数的functoin(要向threadPool插入一个函数,它需要是返回void和ged一个参数-object的函数),例如我想插入这个函数:double foo(int a,double b,string c)
  2. 有没有办法wait在池中进行线程(如连接)?

Iri*_*ium 5

对于第一部分,最简单的方法可能是:

根据您的描述假设一种方法:

public double foo(int a, double b, string c)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

您可以在线程池上对此进行排队:

ThreadPool.QueueUserWorkItem(o => foo(a, b, c));
Run Code Online (Sandbox Code Playgroud)

对于第二部分,虽然您不能在ThreadPool线程上等待,但您可以在线程池上异步调用方法,并等待它们完成(这似乎是您正在寻找的).

同样,假设该Foo方法如上定义.

为Foo定义一个委托:

private delegate double FooDelegate(int a, double b, string c);
Run Code Online (Sandbox Code Playgroud)

然后使用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);
Run Code Online (Sandbox Code Playgroud)

解决评论中提出的问题.如果要并行执行多个函数调用并在继续之前等待它们全部返回,则可以使用:

// 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.
Run Code Online (Sandbox Code Playgroud)