Search Results

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

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

  • F# Async problem.

    - by chrisdew
    Hi, I've written a dummy http server as an exercise in F#. I'm using Mono 2.4.4 on Ubuntu 10.04 x86_64, with MonoDevelop. The following code fails to compile with the error: Error FS0039: The field, constructor or member 'Spawn' is not defined (FS0039) Could someone try this in VisualStudio please, I don't know whether this is a Mono problem, or my problem. I have tried several Async examples from the F# book, and they also all produce similar messages about Async.* methods. Thanks, Chris. #light open System open System.IO open System.Threading open System.Net open System.Net.Sockets open Microsoft.FSharp.Control.CommonExtensions printfn "%s" "Hello World!" let headers = System.Text.Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Length: 37\r\nDate: Sun, 13 Jun 2010 05:30:00 GMT\r\nServer: FSC/0.0.1\r\n\r\n") let content = System.Text.Encoding.ASCII.GetBytes("<html><body>Hello World</body></html>") let serveAsync (client : TcpClient) = async { let out = client.GetStream() do! out.AsyncWrite(headers) do! Async.Sleep 3000 do! out.AsyncWrite(content) do out.Close() } let http_server (ip, port) = let server = new TcpListener(IPAddress.Parse(ip),port) server.Start() while true do let client = server.AcceptTcpClient() printfn "new client" Async.Spawn (serveAsync client) http_server ("0.0.0.0", 1234)

    Read the article

  • Javascript/ajax/php question: sending from server to client works, sending from client to server fai

    - by Jeroen Willemsen
    Hey All, Sorry for reposting(Admins, please delete the other one!). since you guys have been a great help, I was kinda hoping that you could help me once again while having the following question: I am currently trying to work with AJAX by allowing a managerclass in PHP to communicate via an XmlHttpobject with the javascript on the clientside. However, I can send something to the client via JSON, but I cannot read it at the clientside. In fact I am getting the error that the "time" is an undefined index in Session. So I was wondering: what am I doing wrong? The javascriptcode for Ajax: <script type="text/javascript"> var sendReq = GetXmlHttpObject(); var receiveReq = GetXmlHttpObject(); var JSONIn = 0; var JSONOut= 0; //var mTimer; //function to retreive xmlHTTp object for AJAX calls (correct) function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } //Gets the new info from the server function getUpdate() { if (receiveReq.readyState == 4 || receiveReq.readyState == 0) { receiveReq.open("GET", "index.php?json="+JSONIn+"&sid=$this->session", true); receiveReq.onreadystatechange = updateState; receiveReq.send(null); } } //send a message to the server. function sendUpdate(JSONstringsend) { JSONOut=JSONstringsend; if (sendReq.readyState == 4 || sendReq.readyState == 0) { sendReq.open("POST", "index.php?json="+JSONstringsend+"&sid=$this->session", true); sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); alert(JSONstringsend); sendReq.onreadystatechange = updateCycle; sendReq.send(JSONstringsend); } } //When data has been send, update the page. function updateCycle() { getUpdate(); } function updateState() { if (receiveReq.readyState == 4) { // JSONANSWER gets here (correct): var JSONtext = sendReq.responseText; // convert received string to JavaScript object (correct) alert(JSONtext); var JSONobject = JSON.parse(JSONtext); // updates date from the JSONanswer (correct): document.getElementById("dateview").innerHTML= JSONobject.date; } //mTimer = setTimeout('getUpdate();',2000); //Refresh our chat in 2 seconds } </script> The function that actually uses the ajax code: //datepickerdata $(document).ready(function(){ $("#datepicker").datepicker({ onSelect: function(dateText){ var JSONObject = {"date": dateText}; var JSONstring = JSON.stringify(JSONObject); sendUpdate(JSONstring); }, dateFormat: 'dd-mm-yy' }); }); </script> And the PHP code: private function handleReceivedJSon($json){ $this->jsonLocal=array(); $json=$_POST["json"]; $this->jsonDecoded= json_decode($json, true); if(isset($this->jsonDecoded["date"])){ $_SESSION["date"]=$this->jsonDecoded["date"]; $this->useddate=$this->jsonDecoded; } if(isset($this->jsonDecoded["logout"])){ session_destroy(); exit("logout"); } header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" ); header("Cache-Control: no-cache, must-revalidate" ); header("Pragma: no-cache" ); header("Content-Type: text/xml; charset=utf-8"); exit($json); }

    Read the article

  • How to send large objects using boost::asio

    - by Max
    Good day. I'm receiving a large objects via the net using boost::asio. And I have a code: for (int i = 1; i <= num_packets; i++) boost::asio::async_read(socket_, boost::asio::buffer(Obj + packet_size * (i - 1), packet_size), boost::bind(...)); Where My_Class * Obj. I'm in doubt if that approach possible (because i have a pointer to an object here)? Or how it would be better to receive this object using packets of fixed size in bytes? Thanks in advance.

    Read the article

  • Communication between EJB3 Instances (JEE inter-bean communication) possible?

    - by Hank
    I'm designing a part of a JEE6 application, consisting of EJB3 beans. Part of the requirements are multiple parallel (say a few hundred) long running (over days) database hunts. Individual hunts have different search parameters (start time, end time, query filter). Parameters may get changed over time. Currently I'm thinking of the following: SearchController (Stateless Session Bean) formulates a set of search parameters, sends it off to a SearchListener via JMS SearchListener (Message Driven Bean) receives search parameters, instantiates a SearchWorker with the parameters SearchWorker (SLSB) hunts repeatedly through the database; when it finds something, the result is sent off via JMS, and the search continues; when the given 'end-time' has reached, it ends What I'm wondering now: Is there a problem, with EJB3 instances running for days? (Other than that I need to be able to deal with container restarts...) How do I know how many and which EJB instances of SearchWorker are currently running? Is it possible to communicate with them individually (similar to sending a System V signal to a unix process), e.g. to send new parameters, to end an instance, etc..

    Read the article

  • Java process is not terminating after starting an external process

    - by tangens
    On Windows I've started a program "async.cmd" with a ProcessBuilder like this: ProcessBuilder processBuilder = new ProcessBuilder( "async.cmd" ); processBuilder.redirectErrorStream( true ); processBuilder.start(); Then I read the output of the process in a separate thread like this: byte[] buffer = new byte[ 8192 ]; while( !interrupted() ) { int available = m_inputStream.available(); if( available == 0 ) { Thread.sleep( 100 ); continue; } int len = Math.min( buffer.length, available ); len = m_inputStream.read( buffer, 0, len ); if( len == -1 ) { throw new CX_InternalError(); } String outString = new String( buffer, 0, len ); m_output.append( outString ); } Now it happened that the content of the file "async.cmd" was this: REM start a command window start cmd /k The process that started this extenal program terminated (process.waitFor() returned the exit value). Then I sent an readerThread.interrupt() to the reader thread and the thread terminated, too. But there was still a thread running that wasn't terminating. This thread kept my java application running even if it exited its main method. With the debugger (eclipse) I wasn't able to suspend this thread. After I quit the opened command window, my java program exited, too. Question How can I quit my java program while the command window stays open?

    Read the article

  • EXC_BAD_ACCESS on startAsynchronous request using ASIFormDataRequest

    - by user280556
    I am getting EXC_BAD_ACCESS on the Line: [asiUsernameRequest startAsynchronous]; in this code. Spent hours trying to figure it out, but no solution. Any idea? NSString *usernameValue = (NSString*)usernameField.text; NSLog(@"username selected: %@", usernameValue); NSURL *url = [NSURL URLWithString:@"http://www.mywebsite.com/api/usernameCheck"]; //ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; asiUsernameRequest = [[[ASIFormDataRequest alloc] initWithURL:url] retain]; [asiUsernameRequest setPostValue:usernameValue forKey:@"username"]; NSArray *objects = [NSArray arrayWithObjects:@"usernameCheck", nil]; NSArray *keys = [NSArray arrayWithObjects:@"action", nil]; asiUsernameRequest.userInfo = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; [asiUsernameRequest setDelegate:self]; [asiUsernameRequest startAsynchronous];

    Read the article

  • Problems with reading into buffer using boost::asio::async_read

    - by Max
    Good day. I have a Types.hpp file in my project. And within it i have: .... namespace RC { ..... ..... struct ViewSettings { .... }; ..... } In the Server.cpp file I'm including this Types.hpp file, and i have there: class Session { ..... RC::ViewSettings tmp; boost::asio::async_read(socket_, boost::asio::buffer(&tmp, sizeof(RC::ViewSettings)), boost::bind(&Session::Finish_Reading_Data, shared_from_this(), boost::asio::placeholders::error)); ..... } And during the compilation i have an errors: error C2825: 'F': must be a class or namespace when followed by '::' : see reference to class template instantiation 'boost::_bi::result_traits<R,F>' being compiled with [ R=boost::_bi::unspecified, F=void (__thiscall Session::* )(void) ] : see reference to class template instantiation 'boost::_bi::bind_t<R,F,L>' being compiled with [ R=boost::_bi::unspecified, F=void (__thiscall Session::* )(void), L=boost::_bi::list2<boost::_bi::value<boost::shared_ptr<Session>>,boost::arg<1>> ] error C2039: 'result_type' : is not a member of '`global namespace'' And the code like this works in proper way: int w; boost::asio::async_read(socket_, boost::asio::buffer(&w, sizeof(int)), boost::bind(&Session::Handle_Read_Width, shared_from_this(), boost::asio::placeholders::error)); Please, help. What's the problem here? Thanks in advance.

    Read the article

  • Writing a blocking wrapper around twisted's IRC client

    - by Andrey Fedorov
    I'm trying to write a dead-simple interface for an IRC library, like so: import simpleirc connection = simpleirc.Connect('irc.freenode.net', 6667) channel = connection.join('foo') find_command = re.compile(r'google ([a-z]+)').findall for msg in channel: for t in find_command(msg): channel.say("http://google.com/search?q=%s" % t) Working from their example, I'm running into trouble (code is a bit lengthy, so I pasted it here). Since the call to channel.__next__ needs to be returned when the callback <IRCClient instance>.privmsg is called, there doesn't seem to be a clean option. Using exceptions or threads seems like the wrong thing here, is there a simpler (blocking?) way of using twisted that would make this possible?

    Read the article

  • Is there any reason why we don't use subclasses of UIImageView ?

    - by gotye
    Hey everyone, I am currently trying to create a subclass of UIImageView in order to make it download its image from server asynchronously ;) I tried to do it by myself but I haven't gone very far yet :D Anyway, I looked around here and found this : AsyncImageDownload I had a look at the code and the first which springs to mind is : why subclassing a UIView and not a UIImageView ?!? Any thoughts ? Cheers mates, Gotye.

    Read the article

  • C# Multithreaded Domain Design

    - by Thijs Cramer
    Let's say i have a Domain Model that im trying to make compatible with multithreading. The prototype domain is a game domain that consists of Space, SpaceObject, and Location objects. A SpaceObject has the Move method and Asteroid and Ship extend this object with specific properties for the object (Ship has a name and Asteroid has a color) Let's say i want to make the Move method for each object run in a seperate thread. That would be stupid because with 10000 objects, i would have 10000 threads. What would be the best way to seperate the workload between cores/threads? I'm trying to learn the basics of concurrency, and building a small game to prototype a lot of concepts. What i've already done, is build a domain, and a threading model with a timer that launches events based on intervals. If the event occurs i want to update my entire model with the new locations of any SpaceObject. But i don't know how and when to launch new threads with workloads when the event occurs. Some people at work told me that u can't update your core domain multithreaded, because you have to synch everything. But in that case i can't run my game on a dual quadcore server, because it would only use 1 CPU for the hardest tasks. Anyone know what to do here?

    Read the article

  • Ajax jquery async return value

    - by Sonny
    Hi, how can i make this code to don't pause the browser but still return value. You can rewrite this with new method of course. function get_char_val(merk) { var returnValue = null; $.ajax({ type: "POST", async: false, url: "char_info2.php", data: { name: merk }, dataType: "html", success: function(data) { returnValue = data; } }); return returnValue; } var px= get_char_val('x'); var py= get_char_val('y');

    Read the article

  • Using boost::asio::async_read with stdin?

    - by yeus
    hi poeple.. short question: I have a realtime-simulation which is running as a backround process and is connected with pipes to the calling pogramm. I want to send commands to that process using stdin to get certain information from it via stdout. Now because it is a real-time process, it has to be a non blocking input. Is boost::asio::async_read in conjunction with iostream::cin a good idea for this task? how would I use that function if it is feasible? Any more suggestions?

    Read the article

  • Async Socket Listener on separate thread - VB.net

    - by TheHockeyGeek
    I am trying to use the code from Microsoft for an Async Socket connection. It appears the listener runs in the main thread locking the GUI. I am new at both socket connections and multi-threading all at the same time. Having a hard time getting my mind wrapped around this all at once. The code used is at http://msdn.microsoft.com/en-us/library/fx6588te.aspx Using this example, how can I move the listener to its own thread? Public Shared Sub Main() ' Data buffer for incoming data. Dim bytes() As Byte = New [Byte](1023) {} ' Establish the local endpoint for the socket. Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName()) Dim ipAddress As IPAddress = ipHostInfo.AddressList(1) Dim localEndPoint As New IPEndPoint(ipAddress, 11000) ' Create a TCP/IP socket. Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) ' Bind the socket to the local endpoint and listen for incoming connections. listener.Bind(localEndPoint) listener.Listen(100)

    Read the article

  • Does CodeIgniter have to load view in the final step?

    - by Peter
    I have a function function do_something() { // process $this->load->view('some_view', $data); exec('mv /path/to/folder1/*.mp3 /path/to/folder2/'); } My intention is to move files after outputting the view. But apparently it is done before rendering the view. My question is, does $this->load->view(); have to be the final step in a function? I did a little research, and seems like my question is similar to this topic. Correct?

    Read the article

  • How to check when Shell32.Folder.CopyHere() is finished

    - by Jelle Capenberghs
    I need to unzip en zip some files in my application using Shell32. Right now, I use srcFolder.CopyHere(destFolder.Items()) to achieve this. However, my next line of code requires the newly made ZIP-file. But since the CopyHere method is Async, how can I check when it in finished? Right now I use a Thread.Sleep for around 500 ms which is enough for my computer to finish creating the ZIP file, but it's not good code imo. Any ideas? More info/code can be provided if necessary.

    Read the article

  • Multiple responses from identical calls in asynch QUnit + Mockjax tests

    - by NickL
    I'm trying to test some jQuery ajax code using QUnit and Mockjax and have it return different JSON for different tests, like this: $(document).ready(function() { function functionToTest() { return $.getJSON('/echo/json/', { json: JSON.stringify({ "won't": "run" }) }); } module("first"); test("first test", function() { stop(); $.mockjax({ url: '/echo/json/', responseText: JSON.stringify({ hello: 'HEYO!' }) }); functionToTest().done(function(json) { ok(true, json.hello); start(); }); }); test("second test", function() { stop(); $.mockjax({ url: '/echo/json/', responseText: JSON.stringify({ hello: 'HELL NO!' }) }); functionToTest().done(function(json) { ok(true, json.hello); start(); }); }); }); Unfortunately it returns the same response for each call, and order can't be guaranteed, so was wondering how I could set it up so that it was coupled to the actual request and came up with this: $.mockjax({ url: '/echo/json/', response: function(settings) { if (JSON.parse(settings.data.json).order === 1) { this.responseText = JSON.stringify({ hello: 'HEYO!' }); } else { this.responseText = JSON.stringify({ hello: 'HELL NO!' }); } } }); This relies on parameters being sent to the server, but what about requests without parameters, where I still need to test different responses? Is there a way to use QUnit's setup/teardown to do this?

    Read the article

  • How do I pass a reference type to Control.Invoke / display a form centered on the main form

    - by Rubio
    I'm on a thread other than the UI thread and need to display a modal form that's centered on the application's main form. What I usually do is use the width and height of the main form and the modal form to calculate the location, then use the PointToScreen method of the main form to get the location of the modal form. Since I'm on another thread I need to use Control.Invoke to call this method. I just can't figure out how to pass a parameter of type Point to Control.Invoke (params object[]). Value types and String works fine. Or, if someone can find a better way to display a form centered on the main form regardless of thread, that would be great. MessageBox seems to be able to do this (although not modally).

    Read the article

  • Understanding Async Methods in Web Service.

    - by Polaris
    Hello. I consume Java Service in my .NET appliaction. I have one question: When service serialize in .NET he also create Async methods. For example for GetPersons() method service create GetPersonsAsync() which is return void. In which cases I can use this Async methods and what the destination of these methods.

    Read the article

  • jquery two ajax call asynchrounsly in asp.net not working...

    - by eswaran
    Hi all, I am developed an web application in asp.net. In this application I have used jquery ajax for some pages. In this application, when I make two ajax call asynchrounoulsy that would not do as I expceted. what is happening is even the second ajax call finishes i can see the result when the maximum time out ajax call finished. I mean i can see the both results in the same time, not one by one. for an example. I have 3 pages 1) main.aspx - for make two ajax request. 2) totalCount.aspx - to find the total count. (max it takes 7 seconds to return, as corresponding table contains 3 lak records) 3) rowCount.aspx - to find the row details. (max it takes 5 seconds to return result). due to this scene, I have planed to make asyn call in jquery ajax in asp.net. here is my code... function getResult() { getTotalCount(); getRows(); } // it takes max 7 seconds to complete // as it take 7 seconds it should display second.( I mean after the rows dispaying) // but displaying both at the same time after the max time consuming ajax call completed. function getTotalCount() { $.ajax({ type : "POST", async : true, url : "totalCount.aspx?data1=" + document.getElementById("data").value, success : function(responseText) { $("#totalCount").attr("value", responseText); } }) } // it takes max 5 seconds to complete. // after finished, this should display first.( i mean before total count displays) // but displaying both at the same time after the max time consuming ajax call completed. function getRows() { $.ajax({ type : "POST", url : "getrows.aspx?data1=" + document.getElementById("data").value, async : true, success : function(responseText) { $("#getRows").attr("value", responseText); } }); } I would like to know, If there is any possible to make asyn call in jquery ajax in asp.net. I searched in net, I got some points that says we cannot do this in asp.net ref link: http://www.mail-archive.com/[email protected]/msg55125.html if we can do this in asp.net How to do that? thanks r.eswaran.

    Read the article

  • Some Async Socket Code - Help with Garbage Collection?

    - by divinci
    Hi all, I think this question is really about my understanding of Garbage collection and variable references. But I will go ahead and throw out some code for you to look at. // Please note do not use this code for async sockets, just to highlight my question // SocketTransport // This is a simple wrapper class that is used as the 'state' object // when performing Async Socket Reads/Writes public class SocketTransport { public Socket Socket; public byte[] Buffer; public SocketTransport(Socket socket, byte[] buffer) { this.Socket = socket; this.Buffer = buffer; } } // Entry point - creates a SocketTransport, then passes it as the state // object when Asyncly reading from the socket. public void ReadOne(Socket socket) { SocketTransport socketTransport_One = new SocketTransport(socket, new byte[10]); socketTransport_One.Socket.BeginRecieve ( socketTransport_One.Buffer, // Buffer to store data 0, // Buffer offset 10, // Read Length SocketFlags.None // SocketFlags new AsyncCallback(OnReadOne), // Callback when BeginRead completes socketTransport_One // 'state' object to pass to Callback. ); } public void OnReadOne(IAsyncResult ar) { SocketTransport socketTransport_One = ar.asyncState as SocketTransport; ProcessReadOneBuffer(socketTransport_One.Buffer); // Do processing // New Read // Create another! SocketTransport (what happens to first one?) SocketTransport socketTransport_Two = new SocketTransport(socket, new byte[10]); socketTransport_Two.Socket.BeginRecieve ( socketTransport_One.Buffer, 0, 10, SocketFlags.None new AsyncCallback(OnReadTwo), socketTransport_Two ); } public void OnReadTwo(IAsyncResult ar) { SocketTransport socketTransport_Two = ar.asyncState as SocketTransport; .............. So my question is: The first SocketTransport to be created (socketTransport_One) has a strong reference to a Socket object (lets call is ~SocketA~). Once the async read is completed, a new SocketTransport object is created (socketTransport_Two) also with a strong reference to ~SocketA~. Q1. Will socketTransport_One be collected by the garbage collector when method OnReadOne exits? Even though it still contains a strong reference to ~SocketA~ Thanks all!

    Read the article

  • Silverlight Async Design Pattern Issue

    - by Mike Mengell
    I'm in the middle of a Silverlight application and I have a function which needs to call a webservice and using the result complete the rest of the function. My issue is that I would have normally done a synchronous web service call got the result and using that carried on with the function. As Silverlight doesn't support synchronous web service calls without additional custom classes to mimic it, I figure it would be best to go with the flow of async rather than fight it. So my question relates around whats the best design pattern for working with async calls in program flow. In the following example I want to use the myFunction TypeId parameter depending on the return value of the web service call. But I don't want to call the web service until this function is called. How can I alter my code design to allow for the async call? string _myPath; bool myFunction(Guid TypeId) { WS_WebService1.WS_WebService1SoapClient proxy = new WS_WebService1.WS_WebService1SoapClient(); proxy.GetPathByTypeIdCompleted += new System.EventHandler<WS_WebService1.GetPathByTypeIdCompleted>(proxy_GetPathByTypeIdCompleted); proxy.GetPathByTypeIdAsync(TypeId); // Get return value if (myPath == "\\Server1") { //Use the TypeId parameter in here } } void proxy_GetPathByTypeIdCompleted(object sender, WS_WebService1.GetPathByTypeIdCompletedEventArgs e) { string server = e.Result.Server; myPath = '\\' + server; } Thanks in advance, Mike

    Read the article

  • Implementing a robust async stream reader for a console

    - 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 Stream in an event-based manner. The stream, in my scenario, is guaranteed to be a FileStream and there is also an associated StreamReader already present to leverage. The public interface of the class is this: public class MyStreamManager { public event EventHandler<ConsoleOutputReadEventArgs> StandardOutputRead; public void StartSendingEvents(); public void StopSendingEvents(); } Obviously this specific scenario has to do with a console's standard output. 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. Since we are only handing off data from the stream to a consumer, and that consumer may well have inside knowledge about the size and/or format of these chunks, I want to call event subscribers exactly once for each chunk. Otherwise the abstraction breaks down and the subscribers have to buffer the incoming data and reconstruct the chunks themselves using said knowledge. This is much less convenient to the calling code, and detracts from the usefulness of my class. Edit: There are comments below correctly stating that since the data is coming from a stream, there is absolutely nothing that the receiver can infer about the structure of the data unless it is fully prepared to parse it. What I am trying to do here is leverage the "flush the output" "structure" that the owner of the console imparts while writing on it. I am prepared to assume (better: allow my caller to have the option to assume) that the OS will pass me the data written between two flushes of the stream in exactly one piece. 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 (thus preserving the chunks). 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, 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) Maintains the "chunkiness" of the data; this allows the calling code to use inside knowledge of the data without doing any extra work Is almost agnostic to the buffer size (it will work correctly with any size buffer irrespective of the data being read) 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.

    Read the article

  • Threading process in asp.net

    - by Zerotoinfinite
    Hi All, I am using asp.net 3.5 and C#. I have a blog site and I want that whenever user enter any comment, the suscriber related to that post will get the notification. So what I am doing that I am sending mail at the same time as the comment is inserted into the table, which sometimes take time because of the quantity of user. Is their any way that user enter the comment into the database and the send mail function will run asynchornysly which will not interfear user to go ahead with his task. please let me know how to acheieve it in a simplier way. Thanks in advance

    Read the article

  • How can I safely raise events in an AsyncCallback?

    - by cyclotis04
    I'm writing a wrapper class around a TcpClient which raises an event when data arrives. I'm using BeginRead and EndRead, but when the parent form handles the event, it's not running on the UI thread. I do I need to use delegates and pass the context into the callback? I thought that callbacks were a way to avoid this... void ReadCallback(IAsyncResult ar) { int length = _tcpClient.GetStream().EndRead(ar); _stringBuilder.Append(ByteArrayToString(_buffer, length)); BeginRead(); OnStringArrival(EventArgs.Empty); }

    Read the article

  • ItemsControl that loads items one by one asynchronously.

    - by Vinit Sankhe
    Hey Guys, I am creating a custom DataGrid by deriving the traditional tookit based WPF DataGrid. I want a functionality in the grid to load items one by one asynchronously, wherein as soon as ItemsSource is changed i.e. a new collection is Set to the ItemsSource property or the bound collection is Changed dues to items that rae added, moved or removed (wherein the notifications comes to the data grid when the underlying source implements INotifyCollectionChanged such as ObservableCollection). This is because even with virtualising stackpanel underneath the datagrid takes time to load (2-3 seconds delay) to load the data rows when it has several columns and some are template based. With above behavior that delay would "appear" to have reduced giving datagrid a feel that it has the data and is responsive enough to load it. How can I achieve it? Thx Vinit.

    Read the article

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