Beispiel #1
0
        //---------------------------------------------------------------------
        // APM
        //--
        public IAsyncResult BeginWaitEx(int timeout, CancellationToken ctk,
                                        AsyncCallback ucb, object ustate)
        {
            bool result = true;

            lock (_lock)
            {
                if (currentPermits > 0)
                {
                    currentPermits -= 1;
                }
                else if (timeout == 0 || ctk.IsCancellationRequested)
                {
                    result = false;
                }
                else
                {
                    var waiter = new ApmWaiter <Data>(new Data(), ucb, ustate, ctk, timeout, AsyncUnlink);
                    DListNode.AddLast(waiters, waiter);
                    waiter.Enable();
                    return(waiter.AsyncResult);
                }
            }
            // FromResult will invoke the async callbacks, so do it outside of the lock
            if (result)
            {
                return(GenericAsyncResult <bool> .FromResult(ucb, ustate, true, null, true));
            }
            // synchronous completion due to timeout or cancellation
            return(ctk.IsCancellationRequested ?
                   GenericAsyncResult <bool> .FromResult(ucb, ustate, false, new OperationCanceledException(ctk), true) :
                   GenericAsyncResult <bool> .FromResult(ucb, ustate, false, null, true));
        }
Beispiel #2
0
    //
    // File copy using synchronous read and write operations.
    //

    public static IAsyncResult BeginCopySync(Stream src, Stream dst,
                                             AsyncCallback cb, object state)
    {
        byte[] buffer   = new byte[BUFFER_SIZE];
        long   fileSize = 0;

        try {
            int bytesRead;
            while ((bytesRead = src.Read(buffer, 0, buffer.Length)) != 0)
            {
                dst.Write(buffer, 0, bytesRead);
                fileSize += bytesRead;
            }
        } finally {
            src.Close();
            dst.Close();
        }
        return(GenericAsyncResult <long> .FromResult(cb, state, fileSize, null, true));
    }