private static IEnumerator<Int32> PipeServerAsyncEnumerator(AsyncEnumerator ae) { // Each server object performs asynchronous operation on this pipe using (var pipe = new NamedPipeServerStream( "Echo", PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous | PipeOptions.WriteThrough)) { // Asynchronously accept a client connection pipe.BeginWaitForConnection(ae.End(), null); yield return 1; // A client connected, let's accept another client var aeNewClient = new AsyncEnumerator(); aeNewClient.BeginExecute(PipeServerAsyncEnumerator(aeNewClient), aeNewClient.EndExecute); // Accept the client connection pipe.EndWaitForConnection(ae.DequeueAsyncResult()); // Asynchronously read a request from the client Byte[] data = new Byte[1000]; pipe.BeginRead(data, 0, data.Length, ae.End(), null); yield return 1; // The client sent us a request, process it Int32 bytesRead = pipe.EndRead(ae.DequeueAsyncResult()); // Just change to upper case data = Encoding.UTF8.GetBytes( Encoding.UTF8.GetString(data, 0, bytesRead).ToUpper().ToCharArray()); // Asynchronously send the response back to the client pipe.BeginWrite(data, 0, data.Length, ae.End(), null); yield return 1; // The response was sent to the client, close our side of the connection pipe.EndWrite(ae.DequeueAsyncResult()); } // Close happens in a finally block now! }
static IEnumerator <int> ListenerFiber(AsyncEnumerator ae) { var listeningServer = new TcpListener(IPAddress.Loopback, 9998); listeningServer.Start(); while (!ae.IsCanceled()) { listeningServer.BeginAcceptTcpClient(ae.End(0, listeningServer.EndAcceptTcpClient), null); yield return(1); if (ae.IsCanceled()) { yield break; } var clientSocket = listeningServer.EndAcceptTcpClient(ae.DequeueAsyncResult()); var clientAe = new AsyncEnumerator() { SyncContext = null }; clientAe.BeginExecute( ClientFiber(clientAe, clientSocket), ar => { try { clientAe.EndExecute(ar); } catch { } }, null); } }
public void Post(Uri uri, Action <JsonRpcResponse, Exception> resultCallback) { if (uri == null) { throw new ArgumentNullException("uri"); } if (resultCallback == null) { throw new ArgumentNullException("resultCallback"); } try { var ae = new AsyncEnumerator(); ae.BeginExecute(this.GetPostEnumerator(uri, ae, resultCallback), ar => { ae.EndExecute(ar); }); } catch (System.Security.SecurityException ex) { resultCallback(null, ex); } }
public void AddLookups(QuotePage[] pages) { // precondition checking if (pages == null) { throw new ArgumentNullException(); } else if (pages.Length == 0) { throw new ArgumentException(); } foreach (QuotePage page in pages) { if (page == null) { throw new ArgumentException(); } else if (!_cultureMapper.Contains(page.Culture)) { throw new CultureNotSupportedException(page.Culture); } } IsBusy = true; AsyncEnumerator asyncEnumerator = GetAsyncEnumerator(); asyncEnumerator.BeginExecute(ProcessUpdateLookups(asyncEnumerator, pages), asyncEnumerator.EndExecute); }
public void AsyncGetInitData() { Debug.Assert(_Token != null, "token can't be null"); IInitDataProvider provider = new InitDataProvider(); provider.Completed += GetInitDataCompletedCallback; var ae = new AsyncEnumerator(); ae.BeginExecute(provider.AsyncGetInitData(_Token, ae), ae.EndExecute); }
public void AsyncGetLoginData() { Token token = SessionManager.Default.GetToken(_LoginInfo.Parameter.Request.ClientInfo.Session); IInitDataProvider initDataProvider = new InitDataProvider(); initDataProvider.Completed += LoadInitDataCompletedCallback; AsyncEnumerator ae = new AsyncEnumerator(); ae.BeginExecute(initDataProvider.AsyncGetInitData(token, ae), ae.EndExecute); }
private void ExecuteWithAsyncEnumerator() { SetStatus("Working..", StatusState.Busy); AsyncEnumerator ae = new AsyncEnumerator(); ae.BeginExecute(ExecuteWithAsyncEnumerator(ae), ae.EndExecute, null); }
/// <summary> /// Asynchronously copies the contents of the source stream to the destination stream. /// </summary> /// <param name="source">The stream containing the data to be copied.</param> /// <param name="destination">The stream that will receive the copied data.</param> /// <param name="bufferSize">The size of the internal buffer that should be used to copy the data in chunks.</param> /// <param name="reportProgress">A callback method that is called after each chunk is copied to the destination stream.</param> /// <param name="callback">An optional asynchronous callback, to be called when copy completes.</param> /// <param name="state">A user-provided object that distinguishes this particular asynchronous operation from other operations.</param> /// <returns></returns> public static IAsyncResult BeginCopyStream(/* this */ Stream source, Stream destination, Int32 bufferSize, Action <Int64> reportProgress, AsyncCallback callback, Object state) { var ae = new AsyncEnumerator <Int64>("CopyStream") { SyncContext = null }; return(ae.BeginExecute(CopyStream(ae, source, destination, bufferSize, reportProgress), callback, state)); }
static void Main(string[] args) { var ae = new AsyncEnumerator() { SyncContext = null }; var mainOp = ae.BeginExecute(ListenerFiber(ae), null, null); // block until main server is finished ae.EndExecute(mainOp); }
public static void Main() { String[] urls = new String[] { "http://Wintellect.com/", "http://1.1.1.1/", // Demonstrates error recovery "http://www.Devscovery.com/" }; // Demonstrate process AsyncEnumerator ae = new AsyncEnumerator(); ae.EndExecute(ae.BeginExecute(ProcessAllAndEachOps(ae, urls), null)); }
private static IEnumerator <Int32> PipeServerAsyncEnumerator(AsyncEnumerator ae) { // Each server object performs asynchronous operations on this pipe using (var pipe = new NamedPipeServerStream( "Echo", PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous | PipeOptions.WriteThrough)) { // Asynchronously accept a client connection pipe.BeginWaitForConnection(ae.End(), null); yield return(1); // A client connected, let's accept another client var aeNewClient = new AsyncEnumerator(); aeNewClient.BeginExecute(PipeServerAsyncEnumerator(aeNewClient), aeNewClient.EndExecute); // Accept the client connection pipe.EndWaitForConnection(ae.DequeueAsyncResult()); // Asynchronously read a request from the client Byte[] data = new Byte[1000]; pipe.BeginRead(data, 0, data.Length, ae.End(), null); yield return(1); // The client sent us a request, process it. Int32 bytesRead = pipe.EndRead(ae.DequeueAsyncResult()); // Get the timestamp of this client's request DateTime now = DateTime.Now; // We want to save the timestamp of the most-recent client request. Since multiple // clients are running concurrently, this has to be done in a thread-safe way s_gate.BeginRegion(SyncGateMode.Exclusive, ae.End()); // Request exclusive access yield return(1); // The iterator resumes when exclusive access is granted if (s_lastClientRequestTimestamp < now) { s_lastClientRequestTimestamp = now; } s_gate.EndRegion(ae.DequeueAsyncResult()); // Relinquish exclusive access // My sample server just changes all the characters to uppercase // But, you can replace this code with any compute-bound operation data = Encoding.UTF8.GetBytes( Encoding.UTF8.GetString(data, 0, bytesRead).ToUpper().ToCharArray()); // Asynchronously send the response back to the client pipe.BeginWrite(data, 0, data.Length, ae.End(), null); yield return(1); // The response was sent to the client, close our side of the connection pipe.EndWrite(ae.DequeueAsyncResult()); } // Close the pipe }
public void GetImagesAsync(string searchString, Action <IList <Image> > callback, int count = 5) { if (String.IsNullOrEmpty(searchString)) { throw new ArgumentNullException("searchString"); } _searchString = searchString; _totalImages = count; _callback = callback; AsyncEnumerator asyncEnumerator = new AsyncEnumerator(); asyncEnumerator.BeginExecute(GetAllImages(asyncEnumerator), EnumeratorExecutionComplete); }
public void GetImagesAsync(string searchString,Action<IList<Image>> callback, int count = 5) { if (String.IsNullOrEmpty( searchString)) { throw new ArgumentNullException("searchString"); } _searchString = searchString; _totalImages = count; _callback = callback; AsyncEnumerator asyncEnumerator = new AsyncEnumerator(); asyncEnumerator.BeginExecute(GetAllImages(asyncEnumerator), EnumeratorExecutionComplete); }
private IEnumerator <Int32> GetAllImages(AsyncEnumerator ae) { Int32 CurrentPage = 0; Int32 _totalImagesTemp = _totalImages; // while(_totalImagesTemp>0) { AsyncEnumerator asyncE = new AsyncEnumerator(); asyncE.BeginExecute(GetImagesFromGoogle(asyncE, GetGoogleSearchUrl(CurrentPage++), _totalImagesTemp > _numberOfImagesInAPage ? _numberOfImagesInAPage : _totalImagesTemp), ae.EndVoid(0, DiscardWebRequest)); _totalImagesTemp = _totalImagesTemp - _numberOfImagesInAPage; yield return(1); } }
private IEnumerator<Int32> GetAllImages(AsyncEnumerator ae) { Int32 CurrentPage=0; Int32 _totalImagesTemp=_totalImages ; _GoogledImages = new List<Image>(); while(_totalImagesTemp>0) { AsyncEnumerator asyncE = new AsyncEnumerator(); asyncE.BeginExecute(GetImagesFromGoogle(asyncE, GetGoogleSearchUrl(CurrentPage++), _totalImagesTemp > _numberOfImagesInAPage ? _numberOfImagesInAPage : _totalImagesTemp), ae.EndVoid(0, DiscardWebRequest)); _totalImagesTemp = _totalImagesTemp - _numberOfImagesInAPage; yield return 1; } }
private static void ImplementedViaAsyncEnumerator() { // Start 1 server per CPU for (Int32 n = 0; n < Environment.ProcessorCount; n++) { var ae = new AsyncEnumerator(); ae.BeginExecute(PipeServerAsyncEnumerator(ae), ae.EndExecute); } // Now make a 100 client requests against the server for (Int32 n = 0; n < 100; n++) { var ae = new AsyncEnumerator(); ae.BeginExecute(PipeClientAsyncEnumerator(ae, "localhost", "Request #" + n), ae.EndExecute); } }
private void BeginAcceptFileCallback(IAsyncResult result) { FileWatcherFile file; try { file = _listener.EndAcceptFile(result); } catch (ObjectDisposedException) { return; } catch (Exception e) { _logger.Warn("Error on EndAcceptFile", e); StartAcceptingFile(); return; } _logger.DebugFormat("Accepting connection from {0}", file.EndPoint); var enumerator = new AsyncEnumerator("Receiver from " + file.EndPoint); enumerator.BeginExecute(ProcessRequest(file, enumerator), ar => { try { enumerator.EndExecute(ar); } catch (Exception e) { _logger.Warn("Failed to recieve message", e); } }); StartAcceptingFile(); }
private void FlickrButton_Click(object sender, RoutedEventArgs e) { // Initiate a Flickr request String input = Input.Text.Replace(' ', '+'); #if !AsyncEnumerator WebRequest request = HttpWebRequest.Create( new Uri(String.Format("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key={0}&tags={1}&per_page=10", FlickrKey.Key, input))); request.BeginGetResponse(WebRequestComplete, request); #else #if DEBUG AsyncEnumerator.EnableDebugSupport(); #endif AsyncEnumerator ae = new AsyncEnumerator("Query Flickr Photos"); ae.BeginExecute(GetPhotos(ae, input), ae.EndExecute); #endif }
public static void Main() { AsyncEnumerator.EnableDebugSupport(); // Add this to watch window: AsyncEnumerator.GetInProgressList(); // Also, you can hover over a variable that is of my AsyncEnumerator type String[] urls = new String[] { "http://Wintellect.com/", "http://1.1.1.1/", // Demonstrates error recovery "http://www.Devscovery.com/" }; // Demonstrate process AsyncEnumerator ae = new AsyncEnumerator(); ae.SuspendCallback += sr=>{ Console.WriteLine(123); }; ae.ResumeCallback += sr=> { Console.WriteLine(321); }; ae.EndExecute(ae.BeginExecute(ProcessAllAndEachOps(ae, urls), null)); }
internal void UpdateQuotesAsync(QuotePage page) { AsyncEnumerator asyncEnumerator = new AsyncEnumerator(); lock (_asyncEnumerators) { _asyncEnumerators.Add(asyncEnumerator); } asyncEnumerator.BeginExecute(ProcessCollectQuotes(asyncEnumerator, page.Topic, page.Culture, page.Uri, (quotes, topicTranslations) => { page.Items = quotes; page.TopicTranslations = topicTranslations; OnQuotesCollectingCompleted(new QuotesCollectingCompletedEventArgs(page, true)); }), asyncEnumerator.EndExecute); }
internal void CollectQuotesAsync(string topic, CultureInfo culture, Uri uri) { AsyncEnumerator asyncEnumerator = new AsyncEnumerator(); lock (_asyncEnumerators) { _asyncEnumerators.Add(asyncEnumerator); } asyncEnumerator.BeginExecute(ProcessCollectQuotes(asyncEnumerator, topic, culture, uri, (quotes, topicTranslations) => { QuotePage page = new QuotePage(topic, uri, culture, quotes, topicTranslations); OnQuotesCollectingCompleted(new QuotesCollectingCompletedEventArgs(page, false)); _playlist.Add(page); }), asyncEnumerator.EndExecute); }
public static void Transfer( string urlIn, string urlOut, Action<double> onProgress, Action<int> onComplete, Action<Exception> onError) { var ae = new AsyncEnumerator(); ae.BeginExecute(GetAsyncEnumerator(ae, urlIn, urlOut, onProgress, onComplete), ar => { try { ae.EndExecute(ar); } catch (Exception ex) { onError(ex); } }); }
public static void Transfer( string urlIn, string urlOut, Action <double> onProgress, Action <int> onComplete, Action <Exception> onError) { var ae = new AsyncEnumerator(); ae.BeginExecute(GetAsyncEnumerator(ae, urlIn, urlOut, onProgress, onComplete), ar => { try { ae.EndExecute(ar); } catch (Exception ex) { onError(ex); } }); }
public void Send() { var enumerator = new AsyncEnumerator( string.Format("Sending {0} messages to {1}", Messages.Length, Destination) ); logger.DebugFormat("Starting to send {0} messages to {1}", Messages.Length, Destination); enumerator.BeginExecute(SendInternal(enumerator), result => { try { enumerator.EndExecute(result); } catch (Exception exception) { logger.Warn("Failed to send message", exception); Failure(exception); } }); }
public void AddLookup(string topic, CultureInfo culture) { // precondition checking if (topic == null || culture == null) { throw new ArgumentNullException(); } else if (topic.Length == 0) { throw new ArgumentException(); } else if (!_cultureMapper.Contains(culture)) { throw new CultureNotSupportedException(culture); } IsBusy = true; AsyncEnumerator asyncEnumerator = GetAsyncEnumerator(); asyncEnumerator.BeginExecute(ProcessLookup(asyncEnumerator, topic, culture), asyncEnumerator.EndExecute); }
private void BeginAcceptTcpClientCallback(IAsyncResult result) { TcpClient client; try { client = listener.EndAcceptTcpClient(result); } catch (ObjectDisposedException) { return; } logger.DebugFormat("Accepting connection from {0}", client.Client.RemoteEndPoint); var enumerator = new AsyncEnumerator( "Receiver from " + client.Client.RemoteEndPoint ); enumerator.BeginExecute(ProcessRequest(client, enumerator), ar => { try { enumerator.EndExecute(ar); } catch (Exception exception) { logger.Warn("Failed to recieve message", exception); } }); try { listener.BeginAcceptTcpClient(BeginAcceptTcpClientCallback, null); } catch (ObjectDisposedException) { } }
private void GetImages_Click(object sender, RoutedEventArgs e) { BlankImages(); m_ae = new AsyncEnumerator(); m_ae.BeginExecute(DownloadImages(m_ae), m_ae.EndExecute); }
private IEnumerator <int> ProcessRequest(TcpClient client, AsyncEnumerator ae) { try { using (client) using (var stream = client.GetStream()) { var sender = client.Client.RemoteEndPoint; var lenOfDataToReadBuffer = new byte[sizeof(int)]; var lenEnumerator = new AsyncEnumerator(ae.ToString()); try { lenEnumerator.BeginExecute( StreamUtil.ReadBytes(lenOfDataToReadBuffer, stream, lenEnumerator, "length data", false), ae.End()); } catch (Exception exception) { logger.Warn("Unable to read length data from " + sender, exception); yield break; } yield return(1); try { lenEnumerator.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to read length data from " + sender, exception); yield break; } var lengthOfDataToRead = BitConverter.ToInt32(lenOfDataToReadBuffer, 0); if (lengthOfDataToRead < 0) { logger.WarnFormat("Got invalid length {0} from sender {1}", lengthOfDataToRead, sender); yield break; } logger.DebugFormat("Reading {0} bytes from {1}", lengthOfDataToRead, sender); var buffer = new byte[lengthOfDataToRead]; var readBufferEnumerator = new AsyncEnumerator(ae.ToString()); try { readBufferEnumerator.BeginExecute( StreamUtil.ReadBytes(buffer, stream, readBufferEnumerator, "message data", false), ae.End()); } catch (Exception exception) { logger.Warn("Unable to read message data from " + sender, exception); yield break; } yield return(1); try { readBufferEnumerator.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to read message data from " + sender, exception); yield break; } Message[] messages = null; try { messages = SerializationExtensions.ToMessages(buffer); logger.DebugFormat("Deserialized {0} messages from {1}", messages.Length, sender); } catch (Exception exception) { logger.Warn("Failed to deserialize messages from " + sender, exception); } if (messages == null) { try { stream.BeginWrite(ProtocolConstants.SerializationFailureBuffer, 0, ProtocolConstants.SerializationFailureBuffer.Length, ae.End(), null); } catch (Exception exception) { logger.Warn("Unable to send serialization format error to " + sender, exception); yield break; } yield return(1); try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to send serialization format error to " + sender, exception); } yield break; } IMessageAcceptance acceptance = null; byte[] errorBytes = null; try { acceptance = acceptMessages(messages); logger.DebugFormat("All messages from {0} were accepted", sender); } catch (QueueDoesNotExistsException) { logger.WarnFormat("Failed to accept messages from {0} because queue does not exists", sender); errorBytes = ProtocolConstants.QueueDoesNoExiststBuffer; } catch (Exception exception) { errorBytes = ProtocolConstants.ProcessingFailureBuffer; logger.Warn("Failed to accept messages from " + sender, exception); } if (errorBytes != null) { try { stream.BeginWrite(errorBytes, 0, errorBytes.Length, ae.End(), null); } catch (Exception exception) { logger.Warn("Unable to send processing failure from " + sender, exception); yield break; } yield return(1); try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to send processing failure from " + sender, exception); } yield break; } logger.DebugFormat("Sending reciept notice to {0}", sender); try { stream.BeginWrite(ProtocolConstants.RecievedBuffer, 0, ProtocolConstants.RecievedBuffer.Length, ae.End(), null); } catch (Exception exception) { logger.Warn("Could not send reciept notice to " + sender, exception); acceptance.Abort(); yield break; } yield return(1); try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Could not send reciept notice to " + sender, exception); acceptance.Abort(); yield break; } logger.DebugFormat("Reading acknowledgement about accepting messages to {0}", sender); var acknowledgementBuffer = new byte[ProtocolConstants.AcknowledgedBuffer.Length]; var readAcknoweldgement = new AsyncEnumerator(ae.ToString()); try { readAcknoweldgement.BeginExecute( StreamUtil.ReadBytes(acknowledgementBuffer, stream, readAcknoweldgement, "acknowledgement", false), ae.End()); } catch (Exception exception) { logger.Warn("Error reading acknowledgement from " + sender, exception); acceptance.Abort(); yield break; } yield return(1); try { readAcknoweldgement.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Error reading acknowledgement from " + sender, exception); acceptance.Abort(); yield break; } var senderResponse = Encoding.Unicode.GetString(acknowledgementBuffer); if (senderResponse != ProtocolConstants.Acknowledged) { logger.WarnFormat("Sender did not respond with proper acknowledgement, the reply was {0}", senderResponse); acceptance.Abort(); } bool commitSuccessful; try { acceptance.Commit(); commitSuccessful = true; } catch (Exception exception) { logger.Warn("Unable to commit messages from " + sender, exception); commitSuccessful = false; } if (commitSuccessful == false) { bool writeSuccessful; try { stream.BeginWrite(ProtocolConstants.RevertBuffer, 0, ProtocolConstants.RevertBuffer.Length, ae.End(), null); writeSuccessful = true; } catch (Exception e) { logger.Warn("Unable to send revert message to " + sender, e); writeSuccessful = false; } if (writeSuccessful) { yield return(1); try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to send revert message to " + sender, exception); } } } } } finally { var copy = CompletedRecievingMessages; if (copy != null) { copy(); } } }
private void ExecuteJavaTraderRequest() { var ae = new AsyncEnumerator(); ae.BeginExecute(InitDataService.GetInitData(_Request, ae), ae.EndExecute); }
private IEnumerator <int> SendInternal(AsyncEnumerator ae) { try { using (var client = new TcpClient()) { try { client.BeginConnect(Destination.Host, Destination.Port, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Failed to connect to {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return(1); try { client.EndConnect(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Failed to connect to {0} because {1}", Destination, exception); Failure(exception); yield break; } logger.DebugFormat("Successfully connected to {0}", Destination); using (var stream = client.GetStream()) { var buffer = Messages.Serialize(); var bufferLenInBytes = BitConverter.GetBytes(buffer.Length); logger.DebugFormat("Writing length of {0} bytes to {1}", buffer.Length, Destination); try { stream.BeginWrite(bufferLenInBytes, 0, bufferLenInBytes.Length, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return(1); try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } logger.DebugFormat("Writing {0} bytes to {1}", buffer.Length, Destination); try { stream.BeginWrite(buffer, 0, buffer.Length, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return(1); try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } logger.DebugFormat("Successfully wrote to {0}", Destination); var recieveBuffer = new byte[ProtocolConstants.RecievedBuffer.Length]; var readConfirmationEnumerator = new AsyncEnumerator(); try { readConfirmationEnumerator.BeginExecute( StreamUtil.ReadBytes(recieveBuffer, stream, readConfirmationEnumerator, "recieve confirmation", false), ae.End()); } catch (Exception exception) { logger.WarnFormat("Could not read confirmation from {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return(1); try { readConfirmationEnumerator.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Could not read confirmation from {0} because {1}", Destination, exception); Failure(exception); yield break; } var recieveRespone = Encoding.Unicode.GetString(recieveBuffer); if (recieveRespone == ProtocolConstants.QueueDoesNotExists) { logger.WarnFormat( "Response from reciever {0} is that queue does not exists", Destination); Failure(new QueueDoesNotExistsException()); yield break; } else if (recieveRespone != ProtocolConstants.Recieved) { logger.WarnFormat( "Response from reciever {0} is not the expected one, unexpected response was: {1}", Destination, recieveRespone); Failure(null); yield break; } try { stream.BeginWrite(ProtocolConstants.AcknowledgedBuffer, 0, ProtocolConstants.AcknowledgedBuffer.Length, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Failed to write acknowledgement to reciever {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return(1); try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Failed to write acknowledgement to reciever {0} because {1}", Destination, exception); Failure(exception); yield break; } var bookmarks = Success(); buffer = new byte[ProtocolConstants.RevertBuffer.Length]; var readRevertMessage = new AsyncEnumerator(ae.ToString()); bool startingToReadFailed = false; try { readRevertMessage.BeginExecute( StreamUtil.ReadBytes(buffer, stream, readRevertMessage, "revert", true), ae.End()); } catch (Exception) { //more or less expected startingToReadFailed = true; } if (startingToReadFailed) { yield break; } yield return(1); try { readRevertMessage.EndExecute(ae.DequeueAsyncResult()); var revert = Encoding.Unicode.GetString(buffer); if (revert == ProtocolConstants.Revert) { logger.Warn("Got back revert message from receiver, reverting send"); Revert(bookmarks); } } catch (Exception) { // expected, there is nothing to do here, the // reciever didn't report anything for us } } } } finally { var completed = SendCompleted; if (completed != null) { completed(); } } }
private void button1_Click(object sender, RoutedEventArgs e) { var ae = new AsyncEnumerator("String download"); ae.BeginExecute(DownloadString(ae, "http://Wintellect.com/"), ae.EndExecute); }
private IEnumerator <Int32> UploadFileInBlocks(AsyncEnumerator ae, String pathname, CloudBlockBlob blob, Action <Int32> blockUploaded) { Int64 fileLength; using (var fs = new FileStream(pathname, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var mmf = MemoryMappedFile.CreateFromFile(fs, null, fileLength = fs.Length, MemoryMappedFileAccess.Read, null, HandleInheritability.None, false)) { Byte[] uploadedBlocks = new Byte[(fileLength - 1) / m_blockSize + 1]; // Find out which blocks have been uploaded already? blob.BeginDownloadBlockList(BlockListingFilter.Uncommitted, AccessCondition.GenerateEmptyCondition(), null, null, ae.End(), null); yield return(1); try { foreach (ListBlockItem lbi in blob.EndDownloadBlockList(ae.DequeueAsyncResult())) { Int32 blockId = lbi.Name.FromBase64ToInt32(); uploadedBlocks[blockId] = 1; blockUploaded(blockId); } } catch (StorageException e) { if ((HttpStatusCode)e.RequestInformation.HttpStatusCode != HttpStatusCode.NotFound) { throw; } } // Start uploading the remaining blocks: Int32 blocksUploading = 0; foreach (var blockNumber in GetBlockNumbersFromArray(uploadedBlocks)) { // Start uploading up to 'm_concurrency' blocks blocksUploading++; var aeBlock = new AsyncEnumerator("Block #" + blockNumber); aeBlock.BeginExecute(UploadBlock(aeBlock, mmf, blob, blockNumber, (blockNumber == uploadedBlocks.Length - 1) ? fileLength % m_blockSize : m_blockSize), ae.End(), blockNumber); if (blocksUploading < m_concurrency) { continue; } // As each block completes uploading, start uploading a new block (if any are left) yield return(1); blocksUploading--; IAsyncResult result = ae.DequeueAsyncResult(); AsyncEnumerator.FromAsyncResult(result).EndExecute(result); blockUploaded((Int32)result.AsyncState); } // Wait until all blocks have finished uploading and then commit them all for (; blocksUploading > 0; blocksUploading--) { yield return(1); IAsyncResult result = ae.DequeueAsyncResult(); AsyncEnumerator.FromAsyncResult(result).EndExecute(result); blockUploaded((Int32)result.AsyncState); } // Commit all the blocks in order: blob.BeginPutBlockList(Enumerable.Range(0, uploadedBlocks.Length).Select(b => b.ToBase64()), ae.End(), null); yield return(1); blob.EndPutBlockList(ae.DequeueAsyncResult()); } }
public void Login(LoginParameter parameter) { AsyncEnumerator ae = new AsyncEnumerator(); ae.BeginExecute(_LoginProvider.AsyncLogin(parameter, ae), ae.EndExecute); }
public static void Start(String server, String message) { AsyncEnumerator ae = new AsyncEnumerator(); ae.BeginExecute(Process(ae, server, message), ae.EndExecute, null); }
private XElement GetInitDataAction(SerializedObject request, Token token) { XElement result=null; if (token != null && token.AppType == iExchange.Common.AppType.Mobile) { System.Data.DataSet initData = Mobile.Manager.GetInitData(token); List<string> argList = XmlRequestCommandHelper.GetArguments(request.Content); Guid selectedAccountId = (argList != null && argList.Count > 0 ? new Guid(argList[0]) : Guid.Empty); InitDataService.Init(request.Session, initData); result = Mobile.Manager.Initialize(token, initData, selectedAccountId); //test: if (System.Configuration.ConfigurationManager.AppSettings["MobileDebug"]=="true") { ////test place //string s = "<PlacingInstruction AccountId=\"cbcdb06f-141a-415f-bdda-a676bd5759b7\" InstrumentId=\"864ac5d7-b872-45a6-887e-7189463beb12\" PlacingType=\"LimitStop\" EndTime=\"2013-05-02 12:19:07.007\" ExpireType=\"GoodTillSession\" ExpireDate=\"2013-05-02 12:19:07.007\" PriceIsQuote=\"false\" PriceTimestamp=\"2013-05-02 12:19:07.007\"><PlacingOrders><PlacingOrder Id=\"e2a72e0d-ddf6-4d83-8a04-9883a0eee84e\" Lot=\"1\" IsOpen=\"true\" IsBuy=\"false\" SetPrice=\"2.0988\" TradeOption=\"Better\" /></PlacingOrders></PlacingInstruction>"; //XmlDocument doc = new XmlDocument(); //doc.LoadXml(s); //ICollection<Mobile.Server.Transaction> transactionsTest = Mobile.Manager.ConvertPlacingRequest(token, doc.FirstChild); //foreach (Mobile.Server.Transaction transaction in transactionsTest) //{ // string tranCode; // TransactionError error = Application.Default.TradingConsoleServer.Place(token, Application.Default.StateServer, transaction.ToXmlNode(), out tranCode); //} //// test quote //this._Service.Quote(request.Session, "282fa038-1330-43a6-aa87-9d7d01c1a594", 30, 2); // test order query //XElement node = Mobile.Manager.QueryOrder(token, new Guid("1DFC557A-3FB5-4A9F-BD08-E165FA6DFCE6"), 10, 4, 3); //XElement x = new XElement("Result"); //x.Add(node); //XElement e = XElement.Parse("<Transaction ID=\"ec123d66-77af-4403-b739-0bbfa618a37b\" AccountID=\"cbcdb06f-141a-415f-bdda-a676bd5759b7\" InstrumentID=\"864ac5d7-b872-45a6-887e-7189463beb12\" Type=\"2\" SubType=\"1\" OrderType=\"1\" BeginTime=\"2013-05-02 11:52:22\" EndTime=\"2013-05-03 04:00:00\" ExpireType=\"3\" SubmitTime=\"2013-05-10 09:41:07\" ContractSize=\"10001.0000\" SubmitorID=\"79eb2fa2-4ced-4d0e-a283-85adc0136d05\" AssigningOrderID=\"4F23DE3E-3968-440E-829A-3D78685EAA8C\"><Order ID=\"aca88b2e-7640-4a26-9284-6a8993d420e3\" TradeOption=\"1\" IsOpen=\"true\" IsBuy=\"false\" SetPrice=\"2.102\" SetPrice2=\"\" DQMaxMove=\"0\" Lot=\"1.0000\" OriginalLot=\"1.0000\" /></Transaction>"); //Mobile.Server.Transaction transaction = Mobile.Manager.ConvertModifyRequest(token, new Guid("4F23DE3E-3968-440E-829A-3D78685EAA8C"), "2.3", new Guid("11111111-AEF4-4717-8101-522E284DDA6D"), "2.0", null, null, null, null, true); //XElement element = new XElement("Result"); //ICollection<XElement> errorCodes = this.GetPlaceResultForMobile(transaction, token); //XmlNode n = InstrumentManager.Default.UpdateInstrumentSetting(request.Session, new string[] { "27b059c2-1913-44ac-93ec-dc39e9863f1a" }); //string instrumentIds = "6a3fbe21-2e49-46ea-ae93-2be31caa3c6c,babf7daa-af0f-4396-85f2-67e2c97952b7,382be55a-3b33-403e-b9e0-b9eccabd5019,ab98797c-0b0c-427f-8d1b-0de006d153a1,63a02916-28b2-4da1-a65e-59bb1dd4f951,eb82dca7-2625-48df-ac5c-464d160bccbc,282fa038-1330-43a6-aa87-9d7d01c1a594,864ac5d7-b872-45a6-887e-7189463beb12,1bac5d80-7f4a-4b94-98fa-0b76e13fcb1b"; //Dictionary<Guid, Guid> quotePolicyIds = Mobile.Manager.UpdateInstrumentSetting(token, instrumentIds.Split(new char[]{','})); //var state = Trader.Server.Session.SessionManager.Default.GetTradingConsoleState(request.Session); //InstrumentManager.Default.UpdateInstrumentSetting(request.Session, quotePolicyIds); //XElement e= Mobile.Manager.GetChanges(request.Session, true); Dictionary<Guid, Guid> quotePolicyIds = Mobile.Manager.UpdateInstrumentSetting(token, new string[] { }); } } else { AsyncEnumerator ae = new AsyncEnumerator(); ae.BeginExecute(InitDataService.GetInitData(request, null, ae),ae.EndExecute); } return result; }
// AsyncEnumerator class. private static void FetchStockQuotesAsyncEnumerator(WebService svc) { AsyncEnumerator ae = new AsyncEnumerator(); ae.BeginExecute(FetchStockQuotesAsyncEnumerator(ae, svc), ae.EndExecute); }
// The BeginHandler method launches an async op returns immediately // The ASP.NET thread returns back to the thread pool // The thread pool waits on the IAsyncResult and then wakes and calls the EndHandler method private IAsyncResult BeginHandler(Object sender, EventArgs e, AsyncCallback cb, Object extraData) { m_lblPic1.Text = m_lblPic2.Text = null; m_ae = new AsyncEnumerator(); return m_ae.BeginExecute(GetImages(m_ae), cb, extraData); }
private IEnumerator<int> ProcessRequest(TcpClient client, AsyncEnumerator ae) { try { using (client) using (var stream = client.GetStream()) { var sender = client.Client.RemoteEndPoint; var lenOfDataToReadBuffer = new byte[sizeof(int)]; var lenEnumerator = new AsyncEnumerator(ae.ToString()); try { lenEnumerator.BeginExecute( StreamUtil.ReadBytes(lenOfDataToReadBuffer, stream, lenEnumerator, "length data",false), ae.End()); } catch (Exception exception) { logger.Warn("Unable to read length data from " + sender, exception); yield break; } yield return 1; try { lenEnumerator.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to read length data from " + sender, exception); yield break; } var lengthOfDataToRead = BitConverter.ToInt32(lenOfDataToReadBuffer, 0); if (lengthOfDataToRead < 0) { logger.WarnFormat("Got invalid length {0} from sender {1}", lengthOfDataToRead, sender); yield break; } logger.DebugFormat("Reading {0} bytes from {1}", lengthOfDataToRead, sender); var buffer = new byte[lengthOfDataToRead]; var readBufferEnumerator = new AsyncEnumerator(ae.ToString()); try { readBufferEnumerator.BeginExecute( StreamUtil.ReadBytes(buffer, stream, readBufferEnumerator, "message data", false), ae.End()); } catch (Exception exception) { logger.Warn("Unable to read message data from " + sender, exception); yield break; } yield return 1; try { readBufferEnumerator.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to read message data from " + sender, exception); yield break; } Message[] messages = null; try { messages = SerializationExtensions.ToMessages(buffer); logger.DebugFormat("Deserialized {0} messages from {1}", messages.Length, sender); } catch (Exception exception) { logger.Warn("Failed to deserialize messages from " + sender, exception); } if (messages == null) { try { stream.BeginWrite(ProtocolConstants.SerializationFailureBuffer, 0, ProtocolConstants.SerializationFailureBuffer.Length, ae.End(), null); } catch (Exception exception) { logger.Warn("Unable to send serialization format error to " + sender, exception); yield break; } yield return 1; try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to send serialization format error to " + sender, exception); } yield break; } IMessageAcceptance acceptance = null; byte[] errorBytes = null; try { acceptance = acceptMessages(messages); logger.DebugFormat("All messages from {0} were accepted", sender); } catch (QueueDoesNotExistsException) { logger.WarnFormat("Failed to accept messages from {0} because queue does not exists", sender); errorBytes = ProtocolConstants.QueueDoesNoExiststBuffer; } catch (Exception exception) { errorBytes = ProtocolConstants.ProcessingFailureBuffer; logger.Warn("Failed to accept messages from " + sender, exception); } if (errorBytes != null) { try { stream.BeginWrite(errorBytes, 0, errorBytes.Length, ae.End(), null); } catch (Exception exception) { logger.Warn("Unable to send processing failure from " + sender, exception); yield break; } yield return 1; try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to send processing failure from " + sender, exception); } yield break; } logger.DebugFormat("Sending reciept notice to {0}", sender); try { stream.BeginWrite(ProtocolConstants.RecievedBuffer, 0, ProtocolConstants.RecievedBuffer.Length, ae.End(), null); } catch (Exception exception) { logger.Warn("Could not send reciept notice to " + sender, exception); acceptance.Abort(); yield break; } yield return 1; try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Could not send reciept notice to " + sender, exception); acceptance.Abort(); yield break; } logger.DebugFormat("Reading acknowledgement about accepting messages to {0}", sender); var acknowledgementBuffer = new byte[ProtocolConstants.AcknowledgedBuffer.Length]; var readAcknoweldgement = new AsyncEnumerator(ae.ToString()); try { readAcknoweldgement.BeginExecute( StreamUtil.ReadBytes(acknowledgementBuffer, stream, readAcknoweldgement, "acknowledgement", false), ae.End()); } catch (Exception exception) { logger.Warn("Error reading acknowledgement from " + sender, exception); acceptance.Abort(); yield break; } yield return 1; try { readAcknoweldgement.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Error reading acknowledgement from " + sender, exception); acceptance.Abort(); yield break; } var senderResponse = Encoding.Unicode.GetString(acknowledgementBuffer); if (senderResponse != ProtocolConstants.Acknowledged) { logger.WarnFormat("Sender did not respond with proper acknowledgement, the reply was {0}", senderResponse); acceptance.Abort(); } bool commitSuccessful; try { acceptance.Commit(); commitSuccessful = true; } catch (Exception exception) { logger.Warn("Unable to commit messages from " + sender, exception); commitSuccessful = false; } if (commitSuccessful == false) { bool writeSuccessful; try { stream.BeginWrite(ProtocolConstants.RevertBuffer, 0, ProtocolConstants.RevertBuffer.Length, ae.End(), null); writeSuccessful = true; } catch (Exception e) { logger.Warn("Unable to send revert message to " + sender, e); writeSuccessful = false; } if (writeSuccessful) { yield return 1; try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to send revert message to " + sender, exception); } } } } } finally { var copy = CompletedRecievingMessages; if (copy != null) copy(); } }
private IEnumerator<int> SendInternal(AsyncEnumerator ae) { try { using (var client = new TcpClient()) { try { client.BeginConnect(Destination.Host, Destination.Port, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Failed to connect to {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return 1; try { client.EndConnect(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Failed to connect to {0} because {1}", Destination, exception); Failure(exception); yield break; } logger.DebugFormat("Successfully connected to {0}", Destination); using (var stream = client.GetStream()) { var buffer = Messages.Serialize(); var bufferLenInBytes = BitConverter.GetBytes(buffer.Length); logger.DebugFormat("Writing length of {0} bytes to {1}", buffer.Length, Destination); try { stream.BeginWrite(bufferLenInBytes, 0, bufferLenInBytes.Length, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return 1; try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } logger.DebugFormat("Writing {0} bytes to {1}", buffer.Length, Destination); try { stream.BeginWrite(buffer, 0, buffer.Length, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return 1; try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } logger.DebugFormat("Successfully wrote to {0}", Destination); var recieveBuffer = new byte[ProtocolConstants.RecievedBuffer.Length]; var readConfirmationEnumerator = new AsyncEnumerator(); try { readConfirmationEnumerator.BeginExecute( StreamUtil.ReadBytes(recieveBuffer, stream, readConfirmationEnumerator, "recieve confirmation", false), ae.End()); } catch (Exception exception) { logger.WarnFormat("Could not read confirmation from {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return 1; try { readConfirmationEnumerator.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Could not read confirmation from {0} because {1}", Destination, exception); Failure(exception); yield break; } var recieveRespone = Encoding.Unicode.GetString(recieveBuffer); if (recieveRespone == ProtocolConstants.QueueDoesNotExists) { logger.WarnFormat( "Response from reciever {0} is that queue does not exists", Destination); Failure(new QueueDoesNotExistsException()); yield break; } else if(recieveRespone!=ProtocolConstants.Recieved) { logger.WarnFormat( "Response from reciever {0} is not the expected one, unexpected response was: {1}", Destination, recieveRespone); Failure(null); yield break; } try { stream.BeginWrite(ProtocolConstants.AcknowledgedBuffer, 0, ProtocolConstants.AcknowledgedBuffer.Length, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Failed to write acknowledgement to reciever {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return 1; try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Failed to write acknowledgement to reciever {0} because {1}", Destination, exception); Failure(exception); yield break; } var bookmarks = Success(); buffer = new byte[ProtocolConstants.RevertBuffer.Length]; var readRevertMessage = new AsyncEnumerator(ae.ToString()); bool startingToReadFailed = false; try { readRevertMessage.BeginExecute( StreamUtil.ReadBytes(buffer, stream, readRevertMessage, "revert", true), ae.End()); } catch (Exception) { //more or less expected startingToReadFailed = true; } if (startingToReadFailed) yield break; yield return 1; try { readRevertMessage.EndExecute(ae.DequeueAsyncResult()); var revert = Encoding.Unicode.GetString(buffer); if (revert == ProtocolConstants.Revert) { logger.Warn("Got back revert message from receiver, reverting send"); Revert(bookmarks); } } catch (Exception) { // expected, there is nothing to do here, the // reciever didn't report anything for us } } } } finally { var completed = SendCompleted; if (completed != null) completed(); } }
static IEnumerator<Int32> ServerConnectRemote(AsyncEnumerator ae, ServerState server, IPEndPoint ipe, TcpClient local) { // establish a client proxy -> real server connection var remote = new TcpClient(ipe.AddressFamily); var settings = server.settings; remote.NoDelay = true; remote.LingerState.Enabled = false; remote.BeginConnect(IPAddress.Parse(settings.addressforward), settings.portforward, ae.End(), ae); yield return 1; try { remote.EndConnect(ae.DequeueAsyncResult()); } catch (SocketException) { Console.WriteLine("A client failed to connect, has the real server started?"); local.Close(); remote.Close(); remote = null; } if(remote != null) { var bufParam = new ClientBufferParam(); { server.bufferPoolMutex.BeginRegion(SyncGateMode.Exclusive, ae.End()); yield return 1; var res = ae.DequeueAsyncResult(); server.AllocBuffer(ae, bufParam); server.bufferPoolMutex.EndRegion(res); } { var newClientState = new ClientState(local, remote); var remoteAe = new AsyncEnumerator(); var localAe = new AsyncEnumerator(); var bw1 = new BufferWrapper(bufParam.sendbuffer); var bw2 = new BufferWrapper(bufParam.recvbuffer); localAe.BeginExecute(HandleClient(localAe, server, newClientState, local, remote, bw1, server.filterSend), ae.End(), localAe); remoteAe.BeginExecute(HandleClient(remoteAe, server, newClientState, remote, local, bw2, server.filterRecv), ae.End(), remoteAe); Console.WriteLine("Client Connected {0}", local.Client.RemoteEndPoint); yield return 2; for (int x = 0; x < 2; x++) { IAsyncResult ar = ae.DequeueAsyncResult(); ((AsyncEnumerator)ar.AsyncState).EndExecute(ar); } bufParam.sendbuffer = bw1.buffer; bufParam.recvbuffer = bw2.buffer; } { server.bufferPoolMutex.BeginRegion(SyncGateMode.Exclusive, ae.End()); yield return 1; var res = ae.DequeueAsyncResult(); server.FreeBuffer(ae, bufParam); server.bufferPoolMutex.EndRegion(res); } } }
static IEnumerator <int> ClientFiber(AsyncEnumerator ae, TcpClient clientSocket) { Console.WriteLine("ClientFibers ++{0}", Interlocked.Increment(ref clients)); try { // original code to do handshaking and connect to remote host var ns1 = clientSocket.GetStream(); var r1 = new BinaryReader(ns1); var w1 = new BinaryWriter(ns1); if (!(r1.ReadByte() == 5 && r1.ReadByte() == 1)) { yield break; } var c = r1.ReadByte(); for (int i = 0; i < c; ++i) { r1.ReadByte(); } w1.Write((byte)5); w1.Write((byte)0); if (!(r1.ReadByte() == 5 && r1.ReadByte() == 1)) { yield break; } if (r1.ReadByte() != 0) { yield break; } byte[] ipAddr = null; string hostname = null; var type = r1.ReadByte(); switch (type) { case 1: ipAddr = r1.ReadBytes(4); break; case 3: hostname = Encoding.ASCII.GetString(r1.ReadBytes(r1.ReadByte())); break; case 4: throw new Exception(); } var nhport = r1.ReadInt16(); var port = IPAddress.NetworkToHostOrder(nhport); var socketout = new TcpClient(); if (hostname != null) { socketout.Connect(hostname, port); } else { socketout.Connect(new IPAddress(ipAddr), port); } w1.Write((byte)5); w1.Write((byte)0); w1.Write((byte)0); w1.Write(type); switch (type) { case 1: w1.Write(ipAddr); break; case 3: w1.Write((byte)hostname.Length); w1.Write(Encoding.ASCII.GetBytes(hostname), 0, hostname.Length); break; } w1.Write(nhport); using (var ns2 = socketout.GetStream()) { var forwardAe = new AsyncEnumerator() { SyncContext = null }; forwardAe.BeginExecute( ForwardingFiber(forwardAe, ns1, ns2), ae.EndVoid(0, forwardAe.EndExecute), null); yield return(1); if (ae.IsCanceled()) { yield break; } forwardAe.EndExecute(ae.DequeueAsyncResult()); } } finally { Console.WriteLine("ClientFibers --{0}", Interlocked.Decrement(ref clients)); } }
public IAsyncResult BeginUpload(String pathname, CloudBlockBlob blob, Action <Int32> blockUploaded, AsyncCallback callback = null, Object state = null) { var ae = new AsyncEnumerator(); return(ae.BeginExecute(UploadFileInBlocks(ae, pathname, blob, blockUploaded), callback, state)); }
private void m_btnStart_Click(object sender, EventArgs e) { String[] uris = new String[] { "http://Wintellect.com/", "http://1.1.1.1/", // Demonstrates error recovery "http://www.Devscovery.com/" }; // Construct an AsyncEnumerator m_ae = new AsyncEnumerator(); // NOTE: The AsyncEnumerator automatically saves the // Windows Forms SynchronizationContext with it ensuring // that the iterator always runs on the GUI thread; // this allows the iterator to access the UI Controls // Start iterator asynchonously so that GUI thread doesn't block m_ae.BeginExecute(GetWebData(m_ae, uris), m_ae.EndExecute); }
static void Main(string[] args) { Console.WriteLine("Wokf AntiHaxxing Proxy Server by Hunter and Thanatos. Version 1"); var filter = new Filter(); var serverState = new ServerState(filter.Recv, filter.Send); // a new AsyncEnumerator is constructed for the sake of a new thread of execution var ae = new AsyncEnumerator(); var r = ae.BeginExecute(Server(ae, serverState), ae.EndExecute); r.AsyncWaitHandle.WaitOne(); }
private XElement LoginAction(SerializedObject request, Token token) { List<string> argList = XmlRequestCommandHelper.GetArguments(request.Content); XElement result = null; AsyncEnumerator ae = new AsyncEnumerator(); int appType = argList[3].ToInt(); IAsyncResult asyncResult = ae.BeginExecute(LoginManager.Default.Login(request, argList[0], argList[1], argList[2], appType, ae), ae.EndExecute); if ((int)AppType.Mobile == appType) { ae.EndExecute(asyncResult); token = Trader.Server.Session.SessionManager.Default.GetToken(request.Session); result = iExchange3Promotion.Mobile.Manager.Login(token); } //test: if (System.Configuration.ConfigurationManager.AppSettings["MobileDebug"] == "true") { Dictionary<Guid, Guid> quotePolicyIds = Mobile.Manager.UpdateInstrumentSetting(token, new string[] { }); } return result; }
static IEnumerator<Int32> Server(AsyncEnumerator ae, ServerState server) { var sleeper = new CountdownTimer(); var settings = server.settings; var ipe = new IPEndPoint(IPAddress.Parse(settings.addressforward), settings.portforward); var serverSock = new TcpListener(IPAddress.Parse(settings.addresslisten), settings.portlisten); serverSock.Start(20); Console.WriteLine("Server started"); Console.WriteLine("Listening on {0}:{1}", settings.addresslisten, settings.portlisten); Console.WriteLine("Forwarding to {0}:{1}", settings.addressforward, settings.portforward); while (true) { serverSock.BeginAcceptTcpClient(ae.End(), null); yield return 1; TcpClient local = null; try { local = serverSock.EndAcceptTcpClient(ae.DequeueAsyncResult()); local.NoDelay = true; local.LingerState.Enabled = false; } catch (SocketException) { Console.WriteLine("A client failed to connect"); } if(local != null) { // handle client var localAe = new AsyncEnumerator(); localAe.BeginExecute(ServerConnectRemote(localAe, server, ipe, local), localAe.EndExecute, localAe); } } }
// The BeginHandler method launches an op returns immediately // The ASP.NET thread returns back to the thread pool // The thread pool waits on the IAsyncResult and then wakes and calls the EndHandler method private IAsyncResult BeginHandler(Object sender, EventArgs e, AsyncCallback cb, Object extraData) { m_lblPic1.Text = m_lblPic2.Text = null; m_ae = new AsyncEnumerator(); return(m_ae.BeginExecute(GetImages(m_ae), cb, extraData)); }
public void ReadLineAsync() { AsyncEnumerator ae = new AsyncEnumerator(); ae.BeginExecute(Process(ae), ae.EndExecute, null); }
public static void Start(TcpListener server) { AsyncEnumerator ae = new AsyncEnumerator(); ae.BeginExecute(Process(ae, server), ae.EndExecute, null); }