Для первой части, возможно, самый простой подход:
Предполагая метод в ваше описание:
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);
Затем вызвать Foo асинхронно с помощью/EndInvoke методы BeginInvoke на FooDelegate:
// 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.
Вы можете бросить петлю вокруг вашего примера, это то, что мне нужно, но у меня возникли проблемы с тем, как его зацикливать (иметь несколько вызовов функций), когда вы просто сидите там, ожидая результата первого вызова. – ganders
@ganders Я сделал редактирование ответа, чтобы ответить на ваш вопрос. Если вам нужна дополнительная информация, я предлагаю вам задать отдельный вопрос. – Iridium
оцените быстрый ответ Иридиум. Является ли переменная результатов в цикле while предполагаемой переменной asyncResults? – ganders