Пример #1
0
        public void UploadAsync(string path, string token, string message)
        {
            var worker  = new UpdateDelegate(UploadInternal);
            var asyncOp = AsyncOperationManager.CreateOperation(null);

            worker.BeginInvoke(path, token, message, asyncOp, null, null);
        }
Пример #2
0
        /////////////////////////////////////////////////////////////
        ///
        #region Implementation

        // <snippet3>
        // This method starts an asynchronous calculation.
        // First, it checks the supplied task ID for uniqueness.
        // If taskId is unique, it creates a new WorkerEventHandler
        // and calls its BeginInvoke method to start the calculation.
        public virtual void CalculatePrimeAsync(
            int numberToTest,
            object taskId)
        {
            // Create an AsyncOperation for taskId.
            AsyncOperation asyncOp =
                AsyncOperationManager.CreateOperation(taskId);

            // Multiple threads will access the task dictionary,
            // so it must be locked to serialize access.
            lock (userStateToLifetime.SyncRoot)
            {
                if (userStateToLifetime.Contains(taskId))
                {
                    throw new ArgumentException(
                              "Task ID parameter must be unique",
                              "taskId");
                }

                userStateToLifetime[taskId] = asyncOp;
            }

            // Start the asynchronous operation.
            WorkerEventHandler workerDelegate = new WorkerEventHandler(CalculateWorker);

            workerDelegate.BeginInvoke(
                numberToTest,
                asyncOp,
                null,
                null);
        }
Пример #3
0
        /// <summary>
        /// Initializes the Members with their default values
        /// </summary>
        protected void SetDefaults()
        {
            _context          = SynchronizationContext.Current;
            _contextOperation = AsyncOperationManager.CreateOperation(null);

            CreateAndAttachAnalysis();
        }
Пример #4
0
        public void UploadBlobAsync(CloudBlockBlob blob, string localFile, object state)
        {
            TransferType = TransferTypeEnum.Upload;
            //attempt to open the file first so that we throw an exception before getting into the async work
            using (FileStream fs = new FileStream(localFile, FileMode.Open, FileAccess.Read)) { }

            m_Blob     = blob;
            m_FileName = localFile;

            BlobTransferWorkerDelegate worker = new BlobTransferWorkerDelegate(UploadBlobWorker);
            AsyncCallback completedCallback   = new AsyncCallback(TaskCompletedCallback);

            lock (_sync)
            {
                if (TaskIsRunning)
                {
                    throw new InvalidOperationException("The control is currently busy.");
                }

                AsyncOperation async   = AsyncOperationManager.CreateOperation(state);
                MyAsyncContext context = new MyAsyncContext();

                bool cancelled;

                worker.BeginInvoke(context, out cancelled, async, completedCallback, async);

                TaskIsRunning = true;
                TaskContext   = context;
            }
        }
Пример #5
0
        public void ExtractEmailsAsync()
        {
            while (!isTerminating)
            {
                // Check if the folder exists and contains atleast 1 text file
                if (TotalFiles(Scrapers.Pastebin.SaveLocation) == 0)
                {
                    return;
                }

                // Create a worker and a call back
                MergeWorkerDelegate worker            = new MergeWorkerDelegate(ExtractEmailWorker);
                AsyncCallback       completedCallback = new AsyncCallback(MergeCompletedCallBack);

                // Lock the operation and fire up the worker
                lock (_sync)
                {
                    if (isMergeRunning)
                    {
                        throw new InvalidOperationException("Merge is already running, please wait till current merge completes");
                    }

                    AsyncOperation async = AsyncOperationManager.CreateOperation(null);
                    worker.BeginInvoke(completedCallback, async);
                    isMergeRunning = true;
                }
                break;
            }
        }
Пример #6
0
        public void DownloadBlobAsync(ICloudBlob blob, string LocalFile)
        {
            // The class currently stores state in class level variables so calling UploadBlobAsync or DownloadBlobAsync a second time will cause problems.
            // A better long term solution would be to better encapsulate the state, but the current solution works for the needs of my primary client.
            // Throw an exception if UploadBlobAsync or DownloadBlobAsync has already been called.
            lock (WorkingLock)
            {
                if (!Working)
                {
                    Working = true;
                }
                else
                {
                    throw new Exception("BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.");
                }
            }

            // Create an async op in order to raise the events back to the client on the correct thread.
            asyncOp = AsyncOperationManager.CreateOperation(blob);

            TransferType = TransferTypeEnum.Download;
            m_Blob       = blob;
            m_FileName   = LocalFile;

            m_Blob.FetchAttributes();

            FileStream     fs      = new FileStream(m_FileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
            ProgressStream pstream = new ProgressStream(fs);

            pstream.ProgressChanged += pstream_ProgressChanged;
            pstream.SetLength(m_Blob.Properties.Length);
            m_Blob.ServiceClient.DefaultRequestOptions.ParallelOperationThreadCount = 10;
            asyncresult = m_Blob.BeginDownloadToStream(pstream, BlobTransferCompletedCallback, new BlobTransferAsyncState(m_Blob, pstream));
        }
Пример #7
0
        /// <include file='doc\SoundPlayer.uex' path='docs/doc[@for="SoundPlayer.LoadAsync"]/*' />
        public void LoadAsync()
        {
            // if we have a file there is nothing to load - we just pass the file to the PlaySound function
            // if we have a stream, then we start loading the stream async
            //
            if (uri != null && uri.IsFile)
            {
                Debug.Assert(stream == null, "we can't have a stream and a path at the same time");
                isLoadCompleted = true;

                FileInfo fi = new FileInfo(uri.LocalPath);
                if (!fi.Exists)
                {
                    throw new FileNotFoundException(SR.GetString(SR.SoundAPIFileDoesNotExist), this.soundLocation);
                }

                OnLoadCompleted(new AsyncCompletedEventArgs(null, false, null));
                return;
            }

            // if we are actively loading, keep it running
            if (copyThread != null && copyThread.ThreadState == System.Threading.ThreadState.Running)
            {
                return;
            }
            isLoadCompleted = false;
            streamData      = null;
            currentPos      = 0;

            asyncOperation = AsyncOperationManager.CreateOperation(null);

            LoadStream(false);
        }
        public virtual bool Run(bool threaded)
        {
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(this.taskIdentifier);

            this._waitEvent = new AutoResetEvent(false);
            object syncRoot = this.userStateToLifetime.SyncRoot;

            ObjectFlowControl.CheckForSyncLockOnValueType(syncRoot);
            lock (syncRoot)
            {
                if (this.userStateToLifetime.Contains(this.taskIdentifier))
                {
                    Interaction.MsgBox("There is an operation still pending.\r\n\r\nPlease disconnect then reconnect your phone and then try again.", MsgBoxStyle.Exclamation, null);
                    return(false);
                }
                this.userStateToLifetime[this.taskIdentifier] = asyncOp;
            }
            if (threaded)
            {
                new WorkerEventHandler(this.ProcessCommandQueue).BeginInvoke(asyncOp, null, null);
            }
            else
            {
                this.ProcessCommandQueue(asyncOp);
            }
            return(true);
        }
Пример #9
0
        public DirectoryView(string dir, ArrayList myArrayList, Icon plusIcon, Icon minusIcon, ref List <ExtensionIcon> smallImageList, Methods pmyActions)
        {
            _myArrayList    = myArrayList;
            _plusIcon       = plusIcon;
            _minusIcon      = minusIcon;
            _smallImageList = smallImageList;
            // Setup Async
            _oper     = AsyncOperationManager.CreateOperation(null);
            myActions = pmyActions;

            // Fill
            Fill(dir, true, myActions);

            // Setup the FileSystemWatcher
            FileSystemWatcher fsw = new FileSystemWatcher(dir);

            fsw.EnableRaisingEvents = true;

            fsw.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.LastAccess;
            fsw.Changed     += new FileSystemEventHandler(FileSystem_Changed);
            fsw.Created     += new FileSystemEventHandler(FileSystem_Created);
            fsw.Deleted     += new FileSystemEventHandler(FileSystem_Deleted);
            fsw.Renamed     += new RenamedEventHandler(FileSystem_Renamed);

            // Debug info
            WriteDebugThreadInfo("DirectoryView");
        }
 private void NotCompleted(OperationCompletedTracker tracker)
 {
     // This is in a helper method to ensure the JIT doesn't artifically extend the lifetime of the operation.
     AsyncOperationManager.SynchronizationContext = tracker;
     AsyncOperation operation = AsyncOperationManager.CreateOperation(new object());
     Assert.False(tracker.OperationDidComplete);
 }
        public override void SubscribeAsync(object userToken)
        {
            //
            // My Contact is always subscribed. So this is no op. Just call the callback
            //
            if (m_Disposed)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            if (userToken == null)
            {
                throw new ArgumentNullException("userToken");
            }

            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Entering SubscribeAsync() with user token {0}.", userToken);

            lock (AsyncLock){
                if (AsyncOp != null)
                {
                    throw new PeerToPeerException(SR.GetString(SR.Collab_DuplicateSubscribeAsync));
                }

                AsyncOp = AsyncOperationManager.CreateOperation(userToken);
            }

            this.PrepareToRaiseSubscribeCompletedEvent(AsyncOp, new SubscribeCompletedEventArgs(null, this, null, false, userToken));

            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Leaving SubscribeAsync().");
        }
Пример #12
0
        /// <summary>
        /// Downloads a blob to a local file asynchronously.
        /// </summary>
        /// <param name="localFile">The local file.</param>
        /// <exception cref="System.Exception">BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.</exception>
        public ICancellableAsyncResult DownloadBlobAsync(string localFile)
        {
            lock (workingLock)
            {
                if (!working)
                {
                    working = true;
                }
                else
                {
                    throw new Exception("BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.");
                }
            }

            // Create an async op in order to raise the events back to the client on the correct thread.
            asyncOp = AsyncOperationManager.CreateOperation(blob);

            TransferType = TransferTypeEnum.Download;
            fileName     = localFile;

            this.blob.FetchAttributes();

            FileStream     fs      = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
            ProgressStream pstream = new ProgressStream(fs);

            pstream.ProgressChanged += pstream_ProgressChanged;
            pstream.SetLength(this.blob.Properties.Length);
            this.blob.ServiceClient.ParallelOperationThreadCount = 10;
            asyncresult = this.blob.BeginDownloadToStream(pstream, BlobTransferCompletedCallback, new BlobTransferAsyncState(this.blob, pstream));
            return(asyncresult);
        }
Пример #13
0
        /// <summary>
        /// Uploads a file to an Azure blob asynchronously.
        /// </summary>
        /// <param name="localFile">The local file.</param>
        /// <exception cref="System.Exception">BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.</exception>
        public ICancellableAsyncResult UploadBlobAsync(string localFile)
        {
            lock (workingLock)
            {
                if (!working)
                {
                    working = true;
                }
                else
                {
                    throw new Exception("BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.");
                }
            }

            // Attempt to open the file first so that we throw an exception before getting into the async work
            using (var fstemp = new FileStream(localFile, FileMode.Open, FileAccess.Read)) { }

            // Create an async op in order to raise the events back to the client on the correct thread.
            asyncOp = AsyncOperationManager.CreateOperation(this.blob);

            TransferType = TransferTypeEnum.Upload;
            fileName     = localFile;

            var  file     = new FileInfo(fileName);
            long fileSize = file.Length;

            FileStream     fs      = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            ProgressStream pstream = new ProgressStream(fs);

            pstream.ProgressChanged += pstream_ProgressChanged;
            pstream.SetLength(fileSize);
            this.blob.ServiceClient.ParallelOperationThreadCount = 10;
            asyncresult = this.blob.BeginUploadFromStream(pstream, BlobTransferCompletedCallback, new BlobTransferAsyncState(this.blob, pstream));
            return(asyncresult);
        }
Пример #14
0
        public virtual void MatMulAsync(double[,] mat1, double[,] mat2, int size, object taskId)
        {
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(taskId);

            lock (userStateToLifetime.SyncRoot)
            {
                if (userStateToLifetime.Contains(taskId))
                {
                    throw new ArgumentException(
                              "Task ID parameter must be unique",
                              "taskId");
                }

                userStateToLifetime[taskId] = asyncOp;
            }

            // Start the asynchronous operation.
            WorkerEventHandler workerDelegate = new WorkerEventHandler(CalculateWorker);

            workerDelegate.BeginInvoke(
                mat1, mat2, size,
                asyncOp,
                null,
                null);
        }
Пример #15
0
        protected override YahooManaged.Base.DownloadCompletedEventArgs <MarketResult> ConvertDownloadCompletedEventArgs(YahooManaged.Base.DefaultDownloadCompletedEventArgs <MarketResult> e)
        {
            MarketDownloadSettings set = (MarketDownloadSettings)e.Settings;

            if (set.Sectors != null)
            {
                SectorsDownloadCompletedEventArgs args = new SectorsDownloadCompletedEventArgs(e.UserArgs, (SectorResponse)e.Response, set);
                if (AsyncSectorsDownloadCompleted != null)
                {
                    AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(this);
                    asyncOp.Post(new SendOrPostCallback(delegate(object obj) { AsyncSectorsDownloadCompleted(this, (SectorsDownloadCompletedEventArgs)obj); }), args);
                }
                return(args);
            }
            else if (set.Industries != null)
            {
                IndustryDownloadCompletedEventArgs args = new IndustryDownloadCompletedEventArgs(e.UserArgs, (IndustryResponse)e.Response, set);
                if (AsyncIndustriesDownloadCompleted != null)
                {
                    AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(this);
                    asyncOp.Post(new SendOrPostCallback(delegate(object obj) { AsyncIndustriesDownloadCompleted(this, (IndustryDownloadCompletedEventArgs)obj); }), args);
                }
                return(args);
            }
            else
            {
                return(null);
            }
        }
Пример #16
0
        public void Open(string uri, string protocol, ClientAccessPolicyProtocol policyProtocol, bool enableAutoSendPing, int autoSendPingInterval)
        {
            m_AsyncOper = AsyncOperationManager.CreateOperation(null);

            //pass in Origin
            var hostName = HtmlPage.Document.DocumentUri.Host;
            var port     = HtmlPage.Document.DocumentUri.Port;

            string origin = hostName;

            if (port != 80)
            {
                origin += ":" + port;
            }

            m_WebSocket                            = new WebSocket(uri, protocol, cookies: HtmlPage.Document.Cookies, origin: origin);
            m_WebSocket.Opened                    += new EventHandler(m_WebSocket_Opened);
            m_WebSocket.Closed                    += new EventHandler(m_WebSocket_Closed);
            m_WebSocket.MessageReceived           += new EventHandler <MessageReceivedEventArgs>(m_WebSocket_MessageReceived);
            m_WebSocket.Error                     += new EventHandler <ErrorEventArgs>(m_WebSocket_Error);
            m_WebSocket.ClientAccessPolicyProtocol = (policyProtocol == ClientAccessPolicyProtocol.Http) ? SocketClientAccessPolicyProtocol.Http : SocketClientAccessPolicyProtocol.Tcp;
            m_WebSocket.EnableAutoSendPing         = enableAutoSendPing;
            m_WebSocket.AutoSendPingInterval       = autoSendPingInterval;
            m_WebSocket.Open();
        }
Пример #17
0
        void SendAsyncCore(HttpRequestMessage request, object userState)
        {
            if (userState != null)
            {
                CancelManager.EnableCancel(request);
                lock (pendingAsync)
                {
                    HttpStageProcessingAsyncResult pend;
                    if (pendingAsync.TryGetValue(userState, out pend))
                    {
                        if (pend == null)
                        {
                            throw new ArgumentException("userState is not unique", "userState");
                        }
                        else
                        {
                            throw new ArgumentException("userState is already being used for " + pend.HttpAsyncState.request, "userState");
                        }
                    }
                    pendingAsync.Add(userState, null);
                }
            }
            var operation = AsyncOperationManager.CreateOperation(userState);
            var state     = new SendAsyncState(this, operation);
            var result    = this.BeginSendCore(request, SendCompletedCallback, state);

            if (userState != null && !result.IsCompleted)
            {
                lock (pendingAsync)
                {
                    Debug.Assert(pendingAsync[userState] == null);
                    pendingAsync[userState] = result;
                }
            }
        }
Пример #18
0
        public WaitHandle RunAsync()
        {
            if (isRunning)
            {
                throw new InvalidOperationException("Import is already running");
            }

            try {
                /* must be set (as soon as possible) in a function that is _not_ called asynchronously
                 * (i.e. dont call it in ImportThread()) */
                isRunning             = true;
                importSucceeded       = false;
                cancellationRequested = false;
                asyncOperation        = AsyncOperationManager.CreateOperation(null);

                Reset();

                /* invoke the import function on a new thread and return a waithandle */
                Action <string, VolumeDatabase, string, int> it = ImportThread;
                IAsyncResult ar = it.BeginInvoke(sourceDbPath, targetDb, dbDataPath, bufferSize, null, null);
                return(ar.AsyncWaitHandle);
            } catch (Exception) {
                isRunning = false;

                if (asyncOperation != null)
                {
                    asyncOperation.OperationCompleted();
                }

                throw;
            }
        }
Пример #19
0
 /// <summary>
 /// Constructor Engine
 /// </summary>
 /// <param name="rootPath"></param>
 /// <param name="srvType"></param>
 /// <param name="srvIp"></param>
 /// <param name="srvLogin"></param>
 /// <param name="srvPwd"></param>
 public Engine(string rootPath, bool srvType, string srvName, string srvLogin, string srvPwd)
 {
     this.op   = AsyncOperationManager.CreateOperation(null);
     _finfo    = new List <InputSorage>();
     _rootPath = rootPath;
     _isInit   = __InitEngine(srvType, srvName, srvLogin, srvPwd);
 }
        public void DownloadHtmlAsync(Uri address)
        {
            AsyncOperation       asyncOperation = AsyncOperationManager.CreateOperation(null);
            DownloadHtmlCallback callBack       = new DownloadHtmlCallback(InternalDownloadHtmlAsync);

            callBack.BeginInvoke(address, asyncOperation, null, null);
        }
Пример #21
0
 /// <summary>
 /// Creates an instance of the HttpDownloader class
 /// </summary>
 /// <param name="url">Url source string</param>
 /// <param name="destPath">Target file path</param>
 public HttpDownloader(string url, string destPath)
 {
     this.Reset();
     fileURL       = url;
     this.destPath = destPath;
     oprtor        = AsyncOperationManager.CreateOperation(null);
 }
Пример #22
0
        public FileNodeExportViewModel()
        {
            CancelOrCloseCommand = new RelayCommand(DoCancelOrCloseCommand);
            OpenPathCommand      = new RelayCommand(DoOpenPathCommand);

            AsyncOperation = AsyncOperationManager.CreateOperation(this);
        }
Пример #23
0
        public void Reload()
        {
            if (_operation != null)
            {
                return;
            }

            _operation = AsyncOperationManager.CreateOperation(null);
            Reset();
            Show();
            ThreadPool.QueueUserWorkItem(obj =>
            {
                try
                {
                    OnRequestLoad(new GeneralEventArgs <Action <Action> >(_ => OnAction(_)));
                    OnAction(OnLoadSuccess, true);
                }
                catch (Exception ex)
                {
                    Exception = ex;
                    OnAction(OnLoadFailed, true);
                }
                finally
                {
                    _operation = null;
                }
            });
        }
Пример #24
0
        /// <summary>
        /// Upload file and start recognition asynchronously
        /// Performs callbacks:
        ///   UploadFileCompleted
        ///   TaskProcessingCompleted
        /// </summary>
        private void processFileAsync(string filePath, IProcessingSettings settings, object taskId)
        {
            // Create an AsyncOperation for taskId.
            AsyncOperation asyncOp =
                AsyncOperationManager.CreateOperation(taskId);

            // Multiple threads will access the task dictionary,
            // so it must be locked to serialize access.
            lock (processJobs.SyncRoot)
            {
                if (processJobs.Contains(taskId))
                {
                    throw new ArgumentException(
                              "Task ID parameter must be unique",
                              "taskId");
                }

                processJobs[taskId] = asyncOp;
            }

            // Start the asynchronous operation.
            processFileWorkerEventHandler workerDelegate = new processFileWorkerEventHandler(processFileWorker);

            workerDelegate.BeginInvoke(
                filePath, settings,
                asyncOp,
                null,
                null);
        }
Пример #25
0
        private void InitBeforeRun(int threadCount, bool needCreateBarrierForReps = true)
        {
            _repeatCount         = 0;
            _notImplementedReset = false;
            _currentThreadCount  = threadCount;

            if (needCreateBarrierForReps)
            {
                _barrierForReps = new Barrier(threadCount, (b) =>
                {
                    if (!Canceling)
                    {
                        OnRepeatCompleted(
                            new MultiThreadingRepeatEventArgs(++_repeatCount));
                    }
                });
            }

            _canceling      = false;
            _asyncOperation = AsyncOperationManager.CreateOperation(new object());

            Working = true;

            OnBeginningWork(EventArgs.Empty);
        }
Пример #26
0
 public void LoadAsync()
 {
     if ((this.imageLocation == null) || (this.imageLocation.Length == 0))
     {
         throw new InvalidOperationException(System.Windows.Forms.SR.GetString("PictureBoxNoImageLocation"));
     }
     if (!this.pictureBoxState[1])
     {
         this.pictureBoxState[1] = true;
         if (((this.Image == null) || (this.imageInstallationType == ImageInstallationType.ErrorOrInitial)) && (this.InitialImage != null))
         {
             this.InstallNewImage(this.InitialImage, ImageInstallationType.ErrorOrInitial);
         }
         this.currentAsyncLoadOperation = AsyncOperationManager.CreateOperation(null);
         if (this.loadCompletedDelegate == null)
         {
             this.loadCompletedDelegate = new SendOrPostCallback(this.LoadCompletedDelegate);
             this.loadProgressDelegate  = new SendOrPostCallback(this.LoadProgressDelegate);
             this.readBuffer            = new byte[0x1000];
         }
         this.pictureBoxState[0x20] = false;
         this.pictureBoxState[2]    = false;
         this.contentLength         = -1;
         this.tempDownloadStream    = new MemoryStream();
         WebRequest state = WebRequest.Create(this.CalculateUri(this.imageLocation));
         new WaitCallback(this.BeginGetResponseDelegate).BeginInvoke(state, null, null);
     }
 }
Пример #27
0
        /////////////////////////////////////////////////////////////
        ///
        #region 实现

        // 这个方法开始一个异步的计算
        // 首先,它检查提供的taskId是否为unique的,如果是,就创建一个新的 WorkerEventHandler,并调用BeginInvoke方法开始计算
        public virtual void ValidateAsync(
            ref List <ProxyInfo> proxyList,
            object taskId)
        {
            // 为taskId创建一个AsyncOperation对象
            AsyncOperation asyncOp =
                AsyncOperationManager.CreateOperation(taskId);

            // Multiple threads will access the task dictionary,
            // so it must be locked to serialize access.
            lock (userStateToLifetime.SyncRoot)
            {
                if (userStateToLifetime.Contains(taskId))
                {
                    throw new ArgumentException(
                              "Task ID parameter must be unique",
                              "taskId");
                }

                userStateToLifetime[taskId] = asyncOp;
            }

            // 开始异步操作
            WorkerEventHandler workerDelegate = new WorkerEventHandler(CalculateWorker);

            workerDelegate.BeginInvoke(
                ref proxyList,
                asyncOp,
                null,
                null);
        }
Пример #28
0
        //public event EventHandler<TEventArgs<List<>>> ModChatRoomMemberListComplete;
        #endregion

        public Client()
        {
            baseRequest    = new BaseRequest();
            asyncOperation = AsyncOperationManager.CreateOperation(null);
            source         = new CancellationTokenSource();
            factory        = new TaskFactory(source.Token);
        }
Пример #29
0
        /// <summary>
        /// Retrieves the Profile URI for a given entity asynchronously.
        /// </summary>
        /// <param name="command"></param>
        /// <param name="taskId"></param>
        /// <remarks>
        /// This method starts an asynchronous command.
        /// First, it checks the supplied task ID for uniqueness.
        /// If taskId is unique, it creates a new WorkerEventHandler
        /// and calls its BeginInvoke method to start the calculation.
        /// </remarks>
        public virtual void GetProfileAsync(
            string entity,
            int timeout   = DEFAULT_TIMEOUT,
            object taskId = null)
        {
            if (taskId == null)
            {
                taskId = System.Guid.NewGuid();
            }

            // Create an AsyncOperation for taskId.
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(taskId);

            // Multiple threads will access the task dictionary,
            // so it must be locked to serialize access.
            lock (userStateToLifetime.SyncRoot)
            {
                if (userStateToLifetime.Contains(taskId))
                {
                    throw new ArgumentException(
                              "Task ID parameter must be unique",
                              "taskId");
                }

                userStateToLifetime[taskId] = asyncOp;
            }

            // Start the asynchronous operation.
            GetProfileWorkerEventHandler workerDelegate = new GetProfileWorkerEventHandler(CalculateGetProfileWorker);

            workerDelegate.BeginInvoke(entity, timeout, asyncOp, null, null);
        }
Пример #30
0
        public void MovieSearchAsync(string title, object userState)
        {
            AsyncOperation      asyncOp = AsyncOperationManager.CreateOperation(null);
            MovieSearchDelegate worker  = new MovieSearchDelegate(MovieSearchWorker);

            worker.BeginInvoke(title, userState, asyncOp, null, null);
        }