相关疑难解决方法(0)

检测ThreadPool WorkItem是否已完成/等待完成

无论出于何种原因,ThreadPoolQueueWorkItem没有一个返回IAsyncResult或其他一些句柄工作项目,这将使等待,直到它完成.有RegisterWait...方法,但你必须传递WaitHandle和创建它们是昂贵的(请参阅IAsyncResult文档,建议您延迟创建WaitHandle直到请求).任务并行库将解决这个问题,但在可用之前需要等待很长时间.那么,这个设计有什么问题:

public class Concurrent<T> {
    private ManualResetEvent _resetEvent;
    private T _result;

    public Concurrent(Func<T> f) {
        ThreadPool.QueueUserWorkItem(_ => {
                                         _result = f();
                                         if (_resetEvent != null)
                                             _resetEvent.Set();
                                     });
    }

    public WaitHandle WaitHandle {
        get {
            if (_resetEvent == null)
                _resetEvent = new ManualResetEvent(_result != null);
            return _resetEvent;
        }

    ...
Run Code Online (Sandbox Code Playgroud)

编辑:我问了一个关于使用异步委托而不是ThreadPool时出现的问题后续问题.

c# concurrency multithreading asynchronous threadpool

4
推荐指数
1
解决办法
3116
查看次数

在C#中提供方法的同步和异步版本

我正在用C#编写API,我想提供公开可用方法的同步和异步版本.例如,如果我有以下功能:

public int MyFunction(int x, int y)
{
   // do something here
   System.Threading.Thread.Sleep(2000);
   return  x * y;

}
Run Code Online (Sandbox Code Playgroud)

如何创建上述方法的异步版本(可能是BeginMyFunction和EndMyFunction)?是否有不同的方法来实现相同的结果,各种方法的好处是什么?

.net c# asynchronous

4
推荐指数
1
解决办法
2186
查看次数