Search Results

Search found 1226 results on 50 pages for 'asynchronous'.

Page 14/50 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • how get fully result from Asynchronism communication?

    - by rima
    Hi all refer to these post : here1 and here2 at last I solve my problem by build a asynchronous solution,and it work well!!! but there is a problem that i face with it,now my code is like this: class MyProcessStarter { private Process process; private StreamWriter myStreamWriter; private static StringBuilder shellOutput = null; public String GetShellOutput { get { return shellOutput.ToString(); }} public MyProcessStarter(){ shellOutput = new StringBuilder(""); process = new Process(); process.StartInfo.FileName = "sqlplus"; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.OutputDataReceived += new DataReceivedEventHandler(ShellOutputHandler); process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; //process.StartInfo.RedirectStandardError = true; process.Start(); myStreamWriter = process.StandardInput; process.BeginOutputReadLine(); } private static void ShellOutputHandler(object sendingProcess,DataReceivedEventArgs outLine) { if (!String.IsNullOrEmpty(outLine.Data)) shellOutput.Append(Environment.NewLine + outLine.Data); } public void closeConnection() { myStreamWriter.Close(); process.WaitForExit(); process.Close(); } public void RunCommand(string arguments) { myStreamWriter.WriteLine(arguments); myStreamWriter.Flush(); process.WaitForExit(100); Console.WriteLine(shellOutput); Console.WriteLine("============="+Environment.NewLine); process.WaitForExit(2000); Console.WriteLine(shellOutput); } } and my input is like this: myProcesStarter.RunCommand("myusername/mypassword"); Console.writeline(myProcesStarter.GetShellOutput); but take a look at my out put: SQL*Plus: Release 11.1.0.6.0 - Production on Thu May 20 11:57:38 2010 Copyright (c) 1982, 2007, Oracle. All rights reserved. ============= SQL*Plus: Release 11.1.0.6.0 - Production on Thu May 20 11:57:38 2010 Copyright (c) 1982, 2007, Oracle. All rights reserved. Enter user-name: Connected to: Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production With the Partitioning, OLAP, Data Mining and Real Application Testing options as u see the output for run a function is not same in different time!So now would you do me a faver and help me that how I can wait until all the output done in other mean how I can customize my process to wait until output finishing ?? because I want to write a sqlcompiler so I need the exact output of shell. plz help me soon.thanxxxxxxxxxxxx :X

    Read the article

  • jQuery post request is not sent until first post request is compleated

    - by Champ
    I have a function which have a long execution time. public void updateCampaign() { context.Session[processId] = "0|Fetching Lead360 Campaign"; Lead360 objLead360 = new Lead360(); string campaignXML = objLead360.getCampaigns(); string todayDate = DateTime.Now.ToString("dd-MMMM-yyyy"); context.Session[processId] = "1|Creating File for Lead360 Campaign on " + todayDate; string fileName = HttpContext.Current.Server.MapPath("campaigns") + todayDate + ".xml"; objLead360.createFile(fileName, campaignXML); context.Session[processId] = "2|Reading The latest Lead360 Campaign"; string file = File.ReadAllText(fileName); context.Session[processId] = "3|Updating Lead360 Campaign"; string updateStatus = objLead360.updateCampaign(fileName); string[] statusArr = updateStatus.Split('|'); context.Session[processId] = "99|" + statusArr[0] + " New Inserted , " + statusArr[1] + " Updated , With " + statusArr[2] + " Error , "; } So to track the Progress of the function I wrote a another function public void getProgress() { if (context.Session[processId] == null) { string json = "{\"error\":true}"; Response.Write(json); Response.End(); }else{ string[] status = context.Session[processId].ToString().Split('|'); if (status[0] == "99") context.Session.Remove(processId); string json = "{\"error\":false,\"statuscode\":" + status[0] + ",\"statusmsz\":\"" + status[1] + "\" }"; Response.Write(json); Response.End(); } } To call this by jQuery post request is used reqUrl = "AjaxPages/lead360Campaign.aspx?processid=" + progressID + "&action=updatecampaign"; $.post(reqUrl); setTimeout(getProgress, 500); get getProgress is : function getProgress() { reqUrl = "AjaxPages/lead360Campaign.aspx?processid=" + progressID + "&action=getProgress"; $.post(reqUrl, function (response) { var progress = jQuery.parseJSON(response); console.log(progress) if (progress.error) { $("#fetchedCampaign .waitingMsz").html("Some error occured. Please try again later."); $("#fetchedCampaign .waitingMsz").css({ "background": "url(common/images/ajax_error.jpg) no-repeat center 6px" }); return; } if (progress.statuscode == 99) { $("#fetchedCampaign .waitingMsz").html("Update Status :"+ progress.statusmsz ); $("#fetchedCampaign .waitingMsz").css({ "background": "url(common/images/ajax_loded.jpg) no-repeat center 6px" }); return; } $("#fetchedCampaign .waitingMsz").html("Please Wait... " + progress.statusmsz); setTimeout(getProgress, 500); }); } But the problem is that I can't see the intermediate message. Only the last message is been displayed after a long lime of ajax loading message Also on the browser console I just see that after a long time first requested is completed and after that the second request is completed. but there should be for getProgress ? I have checked jquery.doc and it says that $post is an asynchronous request. Can anyone please explain what is wrong with the code or logic?

    Read the article

  • Can an asynchronously fired event run synchronously on a form?

    - by cyclotis04
    [VS 2010 Beta with .Net Framework 3.5] I've written a C# component to asynchronously monitor a socket and raise events when data is received. I set the VB form to show message boxes when the event is raised. What I've noticed is that when the component raises the event synchronously, the message box blocks the component code and locks the form until the user closes the message. When it's raised asynchronously, it neither blocks the code, nor locks the form. What I want is a way to raise an event in such a way that it does not block the code, but is called on the same thread as the form (so that it locks the form until the user selects an option.) Can you help me out? Thanks. [Component] using System; using System.Threading; using System.ComponentModel; namespace mySpace { public delegate void SyncEventHandler(object sender, SyncEventArgs e); public delegate void AsyncEventHandler(object sender, AsyncEventArgs e); public class myClass { readonly object syncEventLock = new object(); readonly object asyncEventLock = new object(); SyncEventHandler syncEvent; AsyncEventHandler asyncEvent; private delegate void WorkerDelegate(string strParam, int intParam); public void DoWork(string strParam, int intParam) { OnSyncEvent(new SyncEventArgs()); AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(null); WorkerDelegate delWorker = new WorkerDelegate(ClientWorker); IAsyncResult result = delWorker.BeginInvoke(strParam, intParam, null, null); } private void ClientWorker(string strParam, int intParam) { Thread.Sleep(2000); OnAsyncEvent(new AsyncEventArgs()); OnAsyncEvent(new AsyncEventArgs()); } public event SyncEventHandler SyncEvent { add { lock (syncEventLock) syncEvent += value; } remove { lock (syncEventLock) syncEvent -= value; } } public event AsyncEventHandler AsyncEvent { add { lock (asyncEventLock) asyncEvent += value; } remove { lock (asyncEventLock) asyncEvent -= value; } } protected void OnSyncEvent(SyncEventArgs e) { SyncEventHandler handler; lock (syncEventLock) handler = syncEvent; if (handler != null) handler(this, e, null, null); // Blocks and locks //if (handler != null) handler.BeginInvoke(this, e, null, null); // Neither blocks nor locks } protected void OnAsyncEvent(AsyncEventArgs e) { AsyncEventHandler handler; lock (asyncEventLock) handler = asyncEvent; //if (handler != null) handler(this, e, null, null); // Blocks and locks if (handler != null) handler.BeginInvoke(this, e, null, null); // Neither blocks nor locks } } } [Form] Imports mySpace Public Class Form1 Public WithEvents component As New mySpace.myClass() Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click component.DoWork("String", 1) End Sub Private Sub component_SyncEvent(ByVal sender As Object, ByVal e As pbxapi.SyncEventArgs) Handles component.SyncEvent MessageBox.Show("Synchronous event", "Raised:", MessageBoxButtons.OK) End Sub Private Sub component_AsyncEvent(ByVal sender As Object, ByVal e As pbxapi.AsyncEventArgs) Handles component.AsyncEvent MessageBox.Show("Asynchronous event", "Raised:", MessageBoxButtons.OK) End Sub End Class

    Read the article

  • Synchronous vs. asynchronous for publish subscribe communication between JavaScript objects

    - by natlee75
    I implemented the publish subscribe pattern in a JavaScript module to be used by entirely client-side oriented JavaScript objects. This module has nothing to do with client-server communications in any way, shape or form. My question is whether it's better for the publish method in such a module to be synchronous or asynchronous, and why. As a very simplified example let's say I'm building a custom UI for an HTML5 video player widget: One of my modules is the "video" module that contains the VIDEO element and handles the various features and events associated with that element. This would probably have a namespace something like "widgets.player.video." Another is the "controls" module that has the various buttons - play, pause, volume, scrub, fullscreen, etc. This might have a namespace along the lines of "widgets.player.controls." These two modules are children of a parent "player" module ("widgets.player" ??), and as such would have no inherent knowledge of each other when instantiated as children of the "player" object. The "controls" elements would obviously need to be able to effect some changes on the video (click "Play" and the video should play), and vice versa (video's "timeUpdate" event fires and the visual display of the current time in the controls should update). I could tightly couple these modules and pass references to each other, but I'd rather take a more loosely coupled approach by setting up a pubsub type module that both can subscribe to and publish from. SO (thanks for bearing with me) in this kind of a scenario is there an advantage one way or another for synchronous publication versus asynchronous publication? I've seen some solutions posted online that allow for either/or with a boolean flag whereas others automatically do it asynchronously. I haven't personally seen an implementation that just automatically goes with synchronous publication... is this because there's no advantage to it? I know that I can accomplish this with features provided by jQuery, but it seems that there may be too much overhead involved here. The publish subscribe pattern can be implemented with relatively lightweight code designed specifically for this particular purpose so I'd rather go with that then a more general purpose eventing system like jQuery's (which I'll use for more general eventing needs :-).

    Read the article

  • Asp.Net MVC and ajax async callback execution order

    - by lrb
    I have been sorting through this issue all day and hope someone can help pinpoint my problem. I have created a "asynchronous progress callback" type functionality in my app using ajax. When I strip the functionality out into a test application I get the desired results. See image below: Desired Functionality When I tie the functionality into my single page application using the same code I get a sort of blocking issue where all requests are responded to only after the last task has completed. In the test app above all request are responded to in order. The server reports a ("pending") state for all requests until the controller method has completed. Can anyone give me a hint as to what could cause the change in behavior? Not Desired Desired Fiddler Request/Response GET http://localhost:12028/task/status?_=1383333945335 HTTP/1.1 X-ProgressBar-TaskId: 892183768 Accept: */* X-Requested-With: XMLHttpRequest Referer: http://localhost:12028/ Accept-Language: en-US Accept-Encoding: gzip, deflate User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0) Connection: Keep-Alive DNT: 1 Host: localhost:12028 HTTP/1.1 200 OK Cache-Control: private Content-Type: text/html; charset=utf-8 Vary: Accept-Encoding Server: Microsoft-IIS/8.0 X-AspNetMvc-Version: 3.0 X-AspNet-Version: 4.0.30319 X-SourceFiles: =?UTF-8?B?QzpcUHJvamVjdHNcVEVNUFxQcm9ncmVzc0Jhclx0YXNrXHN0YXR1cw==?= X-Powered-By: ASP.NET Date: Fri, 01 Nov 2013 21:39:08 GMT Content-Length: 25 Iteration completed... Not Desired Fiddler Request/Response GET http://localhost:60171/_Test/status?_=1383341766884 HTTP/1.1 X-ProgressBar-TaskId: 838217998 Accept: */* X-Requested-With: XMLHttpRequest Referer: http://localhost:60171/Report/Index Accept-Language: en-US Accept-Encoding: gzip, deflate User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0) Connection: Keep-Alive DNT: 1 Host: localhost:60171 Pragma: no-cache Cookie: ASP.NET_SessionId=rjli2jb0wyjrgxjqjsicdhdi; AspxAutoDetectCookieSupport=1; TTREPORTS_1_0=CC2A501EF499F9F...; __RequestVerificationToken=6klOoK6lSXR51zCVaDNhuaF6Blual0l8_JH1QTW9W6L-3LroNbyi6WvN6qiqv-PjqpCy7oEmNnAd9s0UONASmBQhUu8aechFYq7EXKzu7WSybObivq46djrE1lvkm6hNXgeLNLYmV0ORmGJeLWDyvA2 HTTP/1.1 200 OK Cache-Control: private Content-Type: text/html; charset=utf-8 Vary: Accept-Encoding Server: Microsoft-IIS/8.0 X-AspNetMvc-Version: 4.0 X-AspNet-Version: 4.0.30319 X-SourceFiles: =?UTF-8?B?QzpcUHJvamVjdHNcSUxlYXJuLlJlcG9ydHMuV2ViXHRydW5rXElMZWFybi5SZXBvcnRzLldlYlxfVGVzdFxzdGF0dXM=?= X-Powered-By: ASP.NET Date: Fri, 01 Nov 2013 21:37:48 GMT Content-Length: 25 Iteration completed... The only difference in the two requests headers besides the auth tokens is "Pragma: no-cache" in the request and the asp.net version in the response. Thanks Update - Code posted (I probably need to indicate this code originated from an article by Dino Esposito ) var ilProgressWorker = function () { var that = {}; that._xhr = null; that._taskId = 0; that._timerId = 0; that._progressUrl = ""; that._abortUrl = ""; that._interval = 500; that._userDefinedProgressCallback = null; that._taskCompletedCallback = null; that._taskAbortedCallback = null; that.createTaskId = function () { var _minNumber = 100, _maxNumber = 1000000000; return _minNumber + Math.floor(Math.random() * _maxNumber); }; // Set progress callback that.callback = function (userCallback, completedCallback, abortedCallback) { that._userDefinedProgressCallback = userCallback; that._taskCompletedCallback = completedCallback; that._taskAbortedCallback = abortedCallback; return this; }; // Set frequency of refresh that.setInterval = function (interval) { that._interval = interval; return this; }; // Abort the operation that.abort = function () { // if (_xhr !== null) // _xhr.abort(); if (that._abortUrl != null && that._abortUrl != "") { $.ajax({ url: that._abortUrl, cache: false, headers: { 'X-ProgressBar-TaskId': that._taskId } }); } }; // INTERNAL FUNCTION that._internalProgressCallback = function () { that._timerId = window.setTimeout(that._internalProgressCallback, that._interval); $.ajax({ url: that._progressUrl, cache: false, headers: { 'X-ProgressBar-TaskId': that._taskId }, success: function (status) { if (that._userDefinedProgressCallback != null) that._userDefinedProgressCallback(status); }, complete: function (data) { var i=0; }, }); }; // Invoke the URL and monitor its progress that.start = function (url, progressUrl, abortUrl) { that._taskId = that.createTaskId(); that._progressUrl = progressUrl; that._abortUrl = abortUrl; // Place the Ajax call _xhr = $.ajax({ url: url, cache: false, headers: { 'X-ProgressBar-TaskId': that._taskId }, complete: function () { if (_xhr.status != 0) return; if (that._taskAbortedCallback != null) that._taskAbortedCallback(); that.end(); }, success: function (data) { if (that._taskCompletedCallback != null) that._taskCompletedCallback(data); that.end(); } }); // Start the progress callback (if any) if (that._userDefinedProgressCallback == null || that._progressUrl === "") return this; that._timerId = window.setTimeout(that._internalProgressCallback, that._interval); }; // Finalize the task that.end = function () { that._taskId = 0; window.clearTimeout(that._timerId); } return that; };

    Read the article

  • Asynchrony in C# 5 (Part I)

    - by javarg
    I’ve been playing around with the new Async CTP preview available for download from Microsoft. It’s amazing how language trends are influencing the evolution of Microsoft’s developing platform. Much effort is being done at language level today than previous versions of .NET. In these post series I’ll review some major features contained in this release: Asynchronous functions TPL Dataflow Task based asynchronous Pattern Part I: Asynchronous Functions This is a mean of expressing asynchronous operations. This kind of functions must return void or Task/Task<> (functions returning void let us implement Fire & Forget asynchronous operations). The two new keywords introduced are async and await. async: marks a function as asynchronous, indicating that some part of its execution may take place some time later (after the method call has returned). Thus, all async functions must include some kind of asynchronous operations. This keyword on its own does not make a function asynchronous thought, its nature depends on its implementation. await: allows us to define operations inside a function that will be awaited for continuation (more on this later). Async function sample: Async/Await Sample async void ShowDateTimeAsync() {     while (true)     {         var client = new ServiceReference1.Service1Client();         var dt = await client.GetDateTimeTaskAsync();         Console.WriteLine("Current DateTime is: {0}", dt);         await TaskEx.Delay(1000);     } } The previous sample is a typical usage scenario for these new features. Suppose we query some external Web Service to get data (in this case the current DateTime) and we do so at regular intervals in order to refresh user’s UI. Note the async and await functions working together. The ShowDateTimeAsync method indicate its asynchronous nature to the caller using the keyword async (that it may complete after returning control to its caller). The await keyword indicates the flow control of the method will continue executing asynchronously after client.GetDateTimeTaskAsync returns. The latter is the most important thing to understand about the behavior of this method and how this actually works. The flow control of the method will be reconstructed after any asynchronous operation completes (specified with the keyword await). This reconstruction of flow control is the real magic behind the scene and it is done by C#/VB compilers. Note how we didn’t use any of the regular existing async patterns and we’ve defined the method very much like a synchronous one. Now, compare the following code snippet  in contrast to the previuous async/await: Traditional UI Async void ComplicatedShowDateTime() {     var client = new ServiceReference1.Service1Client();     client.GetDateTimeCompleted += (s, e) =>     {         Console.WriteLine("Current DateTime is: {0}", e.Result);         client.GetDateTimeAsync();     };     client.GetDateTimeAsync(); } The previous implementation is somehow similar to the first shown, but more complicated. Note how the while loop is implemented as a chained callback to the same method (client.GetDateTimeAsync) inside the event handler (please, do not do this in your own application, this is just an example).  How it works? Using an state workflow (or jump table actually), the compiler expands our code and create the necessary steps to execute it, resuming pending operations after any asynchronous one. The intention of the new Async/Await pattern is to let us think and code as we normally do when designing and algorithm. It also allows us to preserve the logical flow control of the program (without using any tricky coding patterns to accomplish this). The compiler will then create the necessary workflow to execute operations as the happen in time.

    Read the article

  • Relationship between "Task Parallel Library" and "Task-based Asynchronous Pattern"?

    - by Sid
    In the context of C#, .NET 4/4.5 used for an application running on a web-server, what is the relationship between "Task Parallel Library" and "Task-based Asynchronous Pattern"? I understand one is a library and the other is a pattern. But to dig deeper, is it like "The library is used by the pattern to enforce good practices". I'm also not clear if both are supported in .NET 4.0 (with awake and async keywords) Edit: Seems that awake and async are only in .NET 4.5 ...

    Read the article

  • [C#] WebClient - Upload data, get stream

    - by Barguast
    I have a situation where I want to asynchronously write a series of bytes with WebClient (in much the same way as UploadDataAsync) and get a readable response stream (in the same way as OpenReadAsync). You seem to be able to do the two individually, but not both of them together. Is there a way? Thanks!

    Read the article

  • WCF: Server Not Found - from trace Empty Message when run async but works fine from console app?

    - by MrTortoise
    Todays cause of hair loss has been the following scenario: I have a service that takes 2 strings and returns another. This service uses basicHttpBinding <basicHttpBinding> <binding name="basicHttpNoSec"> <security mode="None" /> </binding> </basicHttpBinding> Anyway, it works fine from a console test app. I have a silverlight app sat on top which implements another basicHttpBinding service that simply reuses the contract in the other service and the silverlight App uses this service. I have a console app that confirms that this service is working and set up with basichttpbinding. I have all the clientAccessPolicy stuff in place. when I run the silverlight app the difference is that it runs everything async ... as such the only message i directly get back rom wcf is server not found. When i enable tracing I dig down to this message - as I know the methods work and the parameteres i pass in will return a valid string i am really puzzled at to what the cause is. any help much appreciated. <E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent"> <System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system"> <EventID>131075</EventID> <Type>3</Type> <SubType Name="Error">0</SubType> <Level>2</Level> <TimeCreated SystemTime="2010-06-07T14:17:40.6639249Z" /> <Source Name="System.ServiceModel" /> <Correlation ActivityID="{8ea9530e-12f4-4a82-9c26-dd2e23264c3c}" /> <Execution ProcessName="aspnet_wp" ProcessID="4616" ThreadID="6" /> <Channel /> <Computer>5JC2Y2J</Computer> </System> <ApplicationData> <TraceData> <DataItem> <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error"> <TraceIdentifier>http://msdn.microsoft.com/en-GB/library/System.ServiceModel.Diagnostics.ThrowingException.aspx</TraceIdentifier> <Description>Throwing an exception.</Description> <AppDomain>/LM/w3svc/1/ROOT/CopSilverlight.Web-1-129203938565564172</AppDomain> <Exception> <ExceptionType>System.ServiceModel.ProtocolException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType> <Message>There is a problem with the XML that was received from the network. See inner exception for more details.</Message> <StackTrace> at System.ServiceModel.Channels.HttpRequestContext.CreateMessage() at System.ServiceModel.Channels.HttpChannelListener.HttpContextReceived(HttpRequestContext context, Action callback) at System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result) at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest() at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest() at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state) at System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) </StackTrace> <ExceptionString>System.ServiceModel.ProtocolException: There is a problem with the XML that was received from the network. See inner exception for more details. ---&gt; System.Xml.XmlException: The body of the message cannot be read because it is empty. --- End of inner exception stack trace ---</ExceptionString> <InnerException> <ExceptionType>System.Xml.XmlException, System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType> <Message>The body of the message cannot be read because it is empty.</Message> <StackTrace> at System.ServiceModel.Channels.HttpRequestContext.CreateMessage() at System.ServiceModel.Channels.HttpChannelListener.HttpContextReceived(HttpRequestContext context, Action callback) at System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result) at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest() at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest() at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state) at System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) </StackTrace> <ExceptionString>System.Xml.XmlException: The body of the message cannot be read because it is empty.</ExceptionString> </InnerException> </Exception> </TraceRecord> </DataItem> </TraceData> </ApplicationData> </E2ETraceEvent>

    Read the article

  • Long-running ASP.NET tasks

    - by John Leidegren
    I know there's a bunch of APIs out there that do this, but I also know that the hosting environment (being ASP.NET) puts restrictions on what you can reliably do in a separate thread. I could be completely wrong, so please correct me if I am, this is however what I think I know. A request typically timeouts after 120 seconds (this is configurable) but eventually the ASP.NET runtime will kill a request that's taking too long to complete. The hosting environment, typically IIS, employs process recycling and can at any point decide to recycle your app. When this happens all threads are aborted and the app restarts. I'm however not sure how aggressive it is, it would be kind of stupid to assume that it would abort a normal ongoing HTTP request but I would expect it to abort a thread because it doesn't know anything about the unit of work of a thread. If you had to create a programming model that easily and reliably and theoretically put a long running task, that would have to run for days, how would you accomplish this from within an ASP.NET application? The following are my thoughts on the issue: I've been thinking a long the line of hosting a WCF service in a win32 service. And talk to the service through WCF. This is however not very practical, because the only reason I would choose to do so, is to send tasks (units of work) from several different web apps. I'd then eventually ask the service for status updates and act accordingly. My biggest concern with this is that it would NOT be a particular great experience if I had to deploy every task to the service for it to be able to execute some instructions. There's also this issue of input, how would I feed this service with data if I had a large data set and needed to chew through it? What I typically do right now is this SELECT TOP 10 * FROM WorkItem WITH (ROWLOCK, UPDLOCK, READPAST) WHERE WorkCompleted IS NULL It allows me to use a SQL Server database as a work queue and periodically poll the database with this query for work. If the work item completed with success, I mark it as done and proceed until there's nothing more to do. What I don't like is that I could theoretically be interrupted at any point and if I'm in-between success and marking it as done, I could end up processing the same work item twice. I might be a bit paranoid and this might be all fine but as I understand it there's no guarantee that that won't happen... I know there's been similar questions on SO before but non really answers with a definitive answer. This is a really common thing, yet the ASP.NET hosting environment is ill equipped to handle long-running work. Please share your thoughts.

    Read the article

  • Silverlight Async Timeout Error

    - by Nath
    Calling through to my Silverlight Enabled WCF-Service in my silverlight application, occasionally users get timeouts. Whats the easiest way to boost the time allowed by the service client for a response? The exact exception thrown is: System.TimeoutException: [HttpRequestTimedOutWithoutDetail] Thanks

    Read the article

  • Async friendly DispatcherTimer wrapper/subclass

    - by Simon_Weaver
    I have a DispatcherTimer running in my code that fire every 30 seconds to update system status from the server. The timer fires in the client even if I'm debugging my server code so if I've been debugging for 5 minutes I may end up with a dozen timeouts in the client. Finally decided I needed to fix this so looking to make a more async / await friendly DispatcherTimer. Code running in DispatcherTimer must be configurable whether it is reentrant or not (i.e. if the task is already running it should not try to run it again) Should be task based (whether or not this requires I actually expose Task at the root is a gray area) Should be able to run async code and await on tasks to complete Whether it wraps or extends DispatcherTimer probably doesn't really matter but wrapping it may be slightly less ambiguous if you don't know how to use it Possibly expose bindable properties for IsRunning for UI

    Read the article

  • Suggestions for doing async I/O with Task Parallel Library

    - by anelson
    I have some high performance file transfer code which I wrote in C# using the Async Programming Model (APM) idiom (eg, BeginRead/EndRead). This code reads a file from a local disk and writes it to a socket. For best performance on modern hardware, it's important to keep more than one outstanding I/O operation in flight whenever possible. Thus, I post several BeginRead operations on the file, then when one completes, I call a BeginSend on the socket, and when that completes I do another BeginRead on the file. The details are a bit more complicated than that but at the high level that's the idea. I've got the APM-based code working, but it's very hard to follow and probably has subtle concurrency bugs. I'd love to use TPL for this instead. I figured Task.Factory.FromAsync would just about do it, but there's a catch. All of the I/O samples I've seen (most particularly the StreamExtensions class in the Parallel Extensions Extras) assume one read followed by one write. This won't perform the way I need. I can't use something simple like Parallel.ForEach or the Extras extension Task.Factory.Iterate because the async I/O tasks don't spend much time on a worker thread, so Parallel just starts up another task, resulting in potentially dozens or hundreds of pending I/O operations; way too much! You can work around that by Waiting on your tasks, but that causes creation of an event handle (a kernel object), and a blocking wait on a task wait handle, which ties up a worker thread. My APM-based implementation avoids both of those things. I've been playing around with different ways to keep multiple read/write operations in flight, and I've managed to do so using continuations that call a method that creates another task, but it feels awkward, and definitely doesn't feel like idiomatic TPL. Has anyone else grappled with an issue like this with the TPL? Any suggestions?

    Read the article

  • Silverlight async calls and anonymous methods....

    - by JLewis
    I know there are a couple of debates on this kind of thing.... At any rate, I have several cases where I need to populate combobox items based on enumerations returned from the WCF service. In an effort to keep code clean, I started this approach. After looking into it more, I don't think the this works as well is initially thought... I am throwing this out to get recommendations/advice/code snippets on how you would do this or how you currently do this. I may be forced to have a seperate, non anonymous method, procedure. I hate doing this for something like this but at the moment, don't see it working another way... EventHandler<GetEnumerationsForTypeCompletedEventArgs> ev = null; ev = delegate(object eventSender, GetEnumerationsForTypeCompletedEventArgs eventArgs) { if (eventArgs.Error == null) { //comboBox.ItemsSource = eventArgs.Result; // populate combox for display purposes (for now) foreach (Enumeration e in eventArgs.Result) { ComboBoxItem cbi = new ComboBoxItem(); cbi.Content = e.EnumerationValueDisplayed; comboBox.Items.Add(cbi); } // remove event so we don't keep adding new events each time we need an enumeration proxy.GetEnumerationsForTypeCompleted -= ev; } }; proxy.GetEnumerationsForTypeCompleted += ev; proxy.GetEnumerationsForTypeAsync(sEnumerationType); Basically in this example we use ev to hold the anonymous method so we can then use ev from within the method to remove it from the events once called. This prevents this method from getting called more than one time. I suspect that the comboBox local var declared before this call, but within the same method, is not always the combobox originally intended but can't really verify that yet. I may add a tag to it to do some tests and populating to verify. Sorry if this is not clear. I can elaborate more if needed. Thanks Jeff

    Read the article

  • Asyncronus javascript rendering widgets

    - by Joe J
    Hey all, I'm creating a javascript widget so third partys (web designers) can post a link on their website and it will render the widget on their site. Currently, I'm doing this with just a script link tag: <div class="some_random_div_in_html_body"> <script type='text/javascript' src='http://remotehost.com/link/to/widget.js'></script> </div> However, this has the side-effect of slowing down a thrid party's website render times of the page if my site is under a load. Therefore, I'd like the third party website to request the widget link from my site asyncronously and then render it on their site when the widget link loads completely. The Google Analytics javascript snippet seems to have a nice bit of asyncronous code that does a nice async request to model off of, but I'm wondering if I can modify it so that it will render content on the third party's site. Using the example below, I want the content of http://mysite.com/link/to/widget.js to render something in the "message" id field. <HTML> <HEAD><TITLE>Third Party Site</TITLE><STYLE>#message { background-color: #eee; } </STYLE></HEAD> <BODY> <div id="message">asdf</div> <script type="text/javascript"> (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'http://mysite.com/link/to/widget.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </BODY> </HTML> I don't know if what I'm trying to do constitutes Cross Site Scripting (still a bit vague on that concept) but am wondering if what I'm trying to do is possible. Or if anyone has any other approaches to creating javascript widgets effectively, I'd appreciate any advice. Thanks for reading this. Joe

    Read the article

  • Understanding the Silverlight Dispatcher

    - by Matt
    I had a Invalid Cross Thread access issue, but a little research and I managed to fix it by using the Dispatcher. Now in my app I have objects with lazy loading. I'd make an Async call using WCF and as usual I use the Dispatcher to update my objects DataContext, however it didn't work for this scenario. I did however find a solution here. Here's what I don't understand. In my UserControl I have code to call an Toggle method on my object. The call to this method is within a Dispatcher like so. Dispatcher.BeginInvoke( () => _CurrentPin.ToggleInfoPanel() ); As I mentioned before this was not enough to satisfy Silverlight. I had to make another Dispatcher call within my object. My object is NOT a UIElement, but a simple class that handles all its own loading/saving. So the problem was fixed by calling Deployment.Current.Dispatcher.BeginInvoke( () => dataContext.Detail = detail ); within my class. Why did I have to call the Dispatcher twice to achieve this? Shouldn't a high-level call be enough? Is there a difference between the Deployment.Current.Dispatcher and the Dispatcher in a UIElement?

    Read the article

  • Async Load JavaScript Files with Callback

    - by Gcoop
    Hi All, I am trying to write an ultra simple solution to load a bunch of JS files asynchronously. I have the following script below so far. However the callback is sometimes called when the scripts aren't actually loaded which causes a variable not found error. If I refresh the page sometimes it just works because I guess the files are coming straight from the cache and thus are there quicker than the callback is called, it's very strange? var Loader = function () { } Loader.prototype = { require: function (scripts, callback) { this.loadCount = 0; this.totalRequired = scripts.length; this.callback = callback; for (var i = 0; i < scripts.length; i++) { this.writeScript(scripts[i]); } }, loaded: function (evt) { this.loadCount++; if (this.loadCount == this.totalRequired && typeof this.callback == 'function') this.callback.call(); }, writeScript: function (src) { var self = this; var s = document.createElement('script'); s.type = "text/javascript"; s.async = true; s.src = src; s.addEventListener('load', function (e) { self.loaded(e); }, false); var head = document.getElementsByTagName('head')[0]; head.appendChild(s); } } Is there anyway to test that a JS file is completely loaded, without putting something in the actual JS file it's self, because I would like to use the same pattern to load libraries out of my control (GMaps etc). Invoking code, just before the tag. var l = new Loader(); l.require([ "ext2.js", "ext1.js"], function() { var config = new MSW.Config(); Refraction.Application().run(MSW.ViewMapper, config); console.log('All Scripts Loaded'); }); Thanks for any help.

    Read the article

  • HttpRequest.BeginWebRequest not executing asynchronously

    - by Shawn Simon
    I have the following code: Private Function CreateRequest() As HttpWebRequest Dim request As HttpWebRequest = HttpWebRequest.Create(_url) request.Method = "POST" request.ContentType = "application/x-www-form-urlencoded" Dim postData As String = String.Join("&", GetPostData().Select(Function(s) String.Format("{0}={1}", s.Key, HttpUtility.UrlEncode(s.Value))).ToArray) Dim data As Byte() = (New ASCIIEncoding).GetBytes(postData) request.Timeout = _maxTimeoutSeconds * 1000 Dim stream = request.GetRequestStream stream.Write(data, 0, data.Length) stream.Close() Return request End Function Public Sub SendAsync(ByVal callback As Action(Of ResponseBase)) Dim request = CreateRequest() _attemptCount += 1 Dim reqID As Integer If _loggingContext IsNot Nothing Then Try reqID = Log.NotesRequest(_url.ToString, GetPostData, _loggingContext) Catch ex As Exception ErrorTracker.LogError(ex) End Try End If Dim responseState As New ResponseState responseState.LoggedNotesRequestID = reqID responseState.Request = request responseState.Callback = callback Dim response = request.BeginGetResponse(New AsyncCallback(AddressOf RespCallback), responseState) End Sub Private Sub RespCallback(ByVal ar As IAsyncResult) Dim responseState As ResponseState = CType(ar.AsyncState, ResponseState) ' Process response... I set up the request to go to a mock server which sleeps for 30 seconds. When I call BeginGetResponse, the application just waits at that line of code for the response. I want it to carry on with the app, and then just run the callback whenever it finishes. This code is run from a web page, and my callback just logs the response and sends an email. I don't want to use to have to wait for the response.

    Read the article

  • Boost asio async vs blocking reads, udp speed/quality

    - by Dolphin
    I have a quick and dirty proof of concept app that I wrote in C# that reads high data rate multicast UDP packets from the network. For various reasons the full implementation will be written in C++ and I am considering using boost asio. The C# version used a thread to receive the data using blocking reads. I had some problems with dropped packets if the computer was heavily loaded (generally with processing those packets in another thread). What I would like to know is if the async read operations in boost (which use overlapped io in windows) will help ensure that I receive the packets and/or reduce the cpu time needed to receive the packets. The single thread doing blocking reads is pretty straightforward, using the async reads seems like a step up in complexity, but I think it would be worth it if it provided higher performance or dropped fewer packets on a heavily loaded system. Currently the data rate should be no higher than 60Mb/s.

    Read the article

  • C++ Winsock non-blocking/async UDP socket

    - by Ragnagard
    Hi all! I'm developping a little data processor in c++ over UDP sockets, and have a thread (just one, and apart the sockets) that process the info received from them. My problem happens when i need to receive info from multiple clients in the socket at the same time. How could i do something like: Socket foo; /* init socket vars and attribs */ while (serving){ thread_processing(foo_info); } for multiple clients (many concurrent access) in c++? I'm using winsocks atm on win32, but just get standard blocking udp sockets working. No gui, it's a console app. I'll appreciate so much an example or pointer to one ;). Thanks in advance.

    Read the article

  • C#: How to set AsyncWaitHandle in Compact Framework?

    - by Thorsten Dittmar
    Hi, I'm using a TcpClient in one of my Compact Framework 2.0 applications. I want to receive some information from a TCP server. As the Compact Framework does not support the timeout mechanisms of the "large" framework, I'm trying to implement my own timeout-thing. Basically, I want to do the following: IAsyncResult result = client.BeginRead(buffer, 0, size, ..., stream); if (!result.AsyncWaitHandle.WaitOne(5000, false)) // Handle timeout private void ReceiveFinished(IAsyncResult ar) { NetworkStream stream = (NetworkStream)ar.AsyncState; int numBytes = stream.EndRead(ar); // SIGNAL IASYNCRESULT.ASYNCWAITHANDLE HERE ... HOW?? } I'd like to call Set for the IAsyncResult.AsyncWaitHandle, but it doesn't have such a method and I don't know which implementation to cast it to. How do I set the wait handle? Or is it automatically set by calling EndRead? The documentation suggests that I'd have to call Set myself... Thanks for any help!

    Read the article

  • Implementing an async "read all currently available data from stream" operation

    - by Jon
    I recently provided an answer to this question: C# - Realtime console output redirection. As often happens, explaining stuff (here "stuff" was how I tackled a similar problem) leads you to greater understanding and/or, as is the case here, "oops" moments. I realized that my solution, as implemented, has a bug. The bug has little practical importance, but it has an extremely large importance to me as a developer: I can't rest easy knowing that my code has the potential to blow up. Squashing the bug is the purpose of this question. I apologize for the long intro, so let's get dirty. I wanted to build a class that allows me to receive input from a console's standard output Stream. Console output streams are of type FileStream; the implementation can cast to that, if needed. There is also an associated StreamReader already present to leverage. There is only one thing I need to implement in this class to achieve my desired functionality: an async "read all the data available this moment" operation. Reading to the end of the stream is not viable because the stream will not end unless the process closes the console output handle, and it will not do that because it is interactive and expecting input before continuing. I will be using that hypothetical async operation to implement event-based notification, which will be more convenient for my callers. The public interface of the class is this: public class ConsoleAutomator { public event EventHandler<ConsoleOutputReadEventArgs> StandardOutputRead; public void StartSendingEvents(); public void StopSendingEvents(); } StartSendingEvents and StopSendingEvents do what they advertise; for the purposes of this discussion, we can assume that events are always being sent without loss of generality. The class uses these two fields internally: protected readonly StringBuilder inputAccumulator = new StringBuilder(); protected readonly byte[] buffer = new byte[256]; The functionality of the class is implemented in the methods below. To get the ball rolling: public void StartSendingEvents(); { this.stopAutomation = false; this.BeginReadAsync(); } To read data out of the Stream without blocking, and also without requiring a carriage return char, BeginRead is called: protected void BeginReadAsync() { if (!this.stopAutomation) { this.StandardOutput.BaseStream.BeginRead( this.buffer, 0, this.buffer.Length, this.ReadHappened, null); } } The challenging part: BeginRead requires using a buffer. This means that when reading from the stream, it is possible that the bytes available to read ("incoming chunk") are larger than the buffer. Remember that the goal here is to read all of the chunk and call event subscribers exactly once for each chunk. To this end, if the buffer is full after EndRead, we don't send its contents to subscribers immediately but instead append them to a StringBuilder. The contents of the StringBuilder are only sent back whenever there is no more to read from the stream. private void ReadHappened(IAsyncResult asyncResult) { var bytesRead = this.StandardOutput.BaseStream.EndRead(asyncResult); if (bytesRead == 0) { this.OnAutomationStopped(); return; } var input = this.StandardOutput.CurrentEncoding.GetString( this.buffer, 0, bytesRead); this.inputAccumulator.Append(input); if (bytesRead < this.buffer.Length) { this.OnInputRead(); // only send back if we 're sure we got it all } this.BeginReadAsync(); // continue "looping" with BeginRead } After any read which is not enough to fill the buffer (in which case we know that there was no more data to be read during the last read operation), all accumulated data is sent to the subscribers: private void OnInputRead() { var handler = this.StandardOutputRead; if (handler == null) { return; } handler(this, new ConsoleOutputReadEventArgs(this.inputAccumulator.ToString())); this.inputAccumulator.Clear(); } (I know that as long as there are no subscribers the data gets accumulated forever. This is a deliberate decision). The good This scheme works almost perfectly: Async functionality without spawning any threads Very convenient to the calling code (just subscribe to an event) Never more than one event for each time data is available to be read Is almost agnostic to the buffer size The bad That last almost is a very big one. Consider what happens when there is an incoming chunk with length exactly equal to the size of the buffer. The chunk will be read and buffered, but the event will not be triggered. This will be followed up by a BeginRead that expects to find more data belonging to the current chunk in order to send it back all in one piece, but... there will be no more data in the stream. In fact, as long as data is put into the stream in chunks with length exactly equal to the buffer size, the data will be buffered and the event will never be triggered. This scenario may be highly unlikely to occur in practice, especially since we can pick any number for the buffer size, but the problem is there. Solution? Unfortunately, after checking the available methods on FileStream and StreamReader, I can't find anything which lets me peek into the stream while also allowing async methods to be used on it. One "solution" would be to have a thread wait on a ManualResetEvent after the "buffer filled" condition is detected. If the event is not signaled (by the async callback) in a small amount of time, then more data from the stream will not be forthcoming and the data accumulated so far should be sent to subscribers. However, this introduces the need for another thread, requires thread synchronization, and is plain inelegant. Specifying a timeout for BeginRead would also suffice (call back into my code every now and then so I can check if there's data to be sent back; most of the time there will not be anything to do, so I expect the performance hit to be negligible). But it looks like timeouts are not supported in FileStream. Since I imagine that async calls with timeouts are an option in bare Win32, another approach might be to PInvoke the hell out of the problem. But this is also undesirable as it will introduce complexity and simply be a pain to code. Is there an elegant way to get around the problem? Thanks for being patient enough to read all of this. Update: I definitely did not communicate the scenario well in my initial writeup. I have since revised the writeup quite a bit, but to be extra sure: The question is about how to implement an async "read all the data available this moment" operation. My apologies to the people who took the time to read and answer without me making my intent clear enough.

    Read the article

  • php script gets two ajax requests, only returns one?

    - by Dan.StackOverflow
    I'll start from the beginning. I'm building a wordpress plugin that does double duty, in that it can be inserted in to a post via a shortcode, or added as a sidebar widget. All it does is output some js to make jquery.post requests to a local php file. The local php file makes a request to a webservice for some data. (I had to do it this way instead of directly querying the web service with jquery.ajax because the url contains a license key that would be public if put in the js). Anyway, When I am viewing a page in the wordpress blog that has both the sidebar widget and the plugin output via shortcode only one of the requests work. I mean it works in that it gets a response back from the php script. Once the page is loaded they both work normally when manually told to. Webpage view - send 2 post requests to my php script - both elements should be filed in, but only one is. My php script is just: <?php if(isset($_POST["zip"])) { // build a curl object, execute the request, // and basically just echo what the curl request returns. } ?> Pretty basic. here is some js some people wanted to see: function widget_getActivities( zip ){ jQuery("#widget_active_list").text(""); jQuery.post("http://localhost/wordpress/wp-content/ActiveAjax.php", { zip: zip}, function(text) { jQuery(text).find("asset").each(function(j, aval){ var html = ""; html += "<a href='" + jQuery(aval).find("trackback").text() + "' target='new'> " + jQuery(aval).find("assetName").text() + "</a><b> at </b>"; jQuery("location", aval).each(function(i, val){ html += jQuery("locationName", val).text() + " <b> on </b>"; }); jQuery("date", aval).each(function(){ html += jQuery("startDate", aval).text(); <!--jQuery("#widget_active_list").append("<div id='ActivityEntry'>" + html + " </div>");--> jQuery("#widget_active_list") .append(jQuery("<div>") .addClass("widget_ActivityEntry") .html(html) .bind("mouseenter", function(){ jQuery(this).animate({ fontSize: "20px", lineHeight: "1.2em" }, 50); }) .bind("mouseleave", function(){ jQuery(this).animate({ fontSize: "10px", lineHeight: "1.2em" }, 50); }) ); }); }); }); } Now imagine there is another function identical to this one except everything that is prepended with 'widget_' isn't prepended. These two functions get called separately via: jQuery(document).ready(function(){ w_zip = jQuery("#widget_zip").val(); widget_getActivities( w_zip ); jQuery("#widget_updateZipLink").click(function() { //start function when any update link is clicked widget_c_zip = jQuery("#widget_zip").val(); if (undefined == widget_c_zip || widget_c_zip == "" || widget_c_zip.length != 5) jQuery("#widget_zipError").text("Bad zip code"); else widget_getActivities( widget_c_zip ); }); }) I can see in my apache logs that both requests are being made. I'm guessing it is some sort of race condition but that doesn't make ANY sense. I'm new to all this, any ideas? EDIT: I've come up with a sub-optimal solution. I have my widget detect if the plugin is also being used on the page, and if so it waits for 3 seconds before performing the request. But I have a feeling this same thing is going to happen if multiple clients perform a page request at the same time that triggers one of the requests to my php script, because I believe the problem is in the php script, which is scary.

    Read the article

  • loading js files and other dependent js files asynchronously

    - by taber
    I'm looking for a clean way to asynchronously load the following types of javascript files: a "core" js file (hmm, let's just call it, oh i don't know, "jquery!" haha), x number of js files that are dependent on the "core" js file being loaded, and y number of other unrelated js files. I have a couple ideas of how to go about it, but not sure what the best way is. I'd like to avoid loading scripts in the document body. So for example, I want the following 4 javascript files to load asynchronously, appropriately named: /js/my-contact-page-js-functions.js // unrelated/independent script /js/jquery-1.3.2.min.js // the "core" script /js/jquery.color.min.js // dependent on jquery being loaded http://thirdparty.com/js/third-party-tracking-script.js // another unrelated/independent script But this won't work because it's not guaranteed that jQuery is loaded before the color plugin... (function() { a=[ '/js/my-contact-page-functions.js', '/js/jquery-1.4.2.min.js', '/js/jquery.color.js', 'http://cdn.thirdparty.com/third-party-tracking-script.js', ], d=document, h=d.getElementsByTagName('head')[0], s, i, l=a.length; for(i=0;i<l;i++){ s=d.createElement('script'); s.type='text/javascript'; s.async=true; s.src=a[i]; h.appendChild(s); } })(); Is it pretty much not possible to load jquery and the color plugin asynchronously? (Since the color plugin requires that jQuery is loaded first.) The first method I was considering is to just combine the color plugin script with jQuery source into one file. Then another idea I had was loading the color plugin like so: $(window).ready(function() { $.getScript("/js/jquery.color.js"); }); Anyone have any thoughts on how you'd go about this? Thanks!

    Read the article

  • Write asynchronously to file in perl

    - by Stefhen
    Basically I would like to: Read a large amount of data from the network into an array into memory. Asynchronously write this array data, running it thru bzip2 before it hits the disk. repeat.. Is this possible? If this is possible, I know that I will have to somehow read the next pass of data into a different array as the AIO docs say that this array must not be altered before the async write is complete. I would like to background all of my writes to disk in order as the bzip2 pass is going to take much longer than the network read. Is this doable? Below is a simple example of what I think is needed, but this just reads a file into array @a for testing. use warnings; use strict; use EV; use IO::AIO; use Compress::Bzip2; use FileHandle; use Fcntl; my @a; print "loading to array...\n"; while(<>) { $a[$. - 1] = $_; } print "array loaded...\n"; my $aio_w = EV::io IO::AIO::poll_fileno, EV::WRITE, \&IO::AIO::poll_cb; aio_open "./out", O_WRONLY || O_NONBLOCK, 0, sub { my $fh = shift or die "error while opening: $!\n"; aio_write $fh, undef, undef, $a, -1, sub { $_[0] > 0 or die "error: $!\n"; EV::unloop; }; }; EV::loop EV::LOOP_NONBLOCK;

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >