Search Results

Search found 1356 results on 55 pages for 'asynchronous challenged'.

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

  • 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

  • Async Call To Services

    - by Pita.O
    Hi Is there any time it would not be a good idea to call web services async? My data layer is a REST-based interface and I thinking of adopting an async-only approach to all the CRUD in the system. Is there anything I should know?

    Read the article

  • Guaranteed semaphore order?

    - by Steve_
    The documentation for the .NET Semaphore class states that: There is no guaranteed order, such as FIFO or LIFO, in which blocked threads enter the semaphore. In this case, if I want a guaranteed order (either FIFO or LIFO), what are my options? Is this something that just isn't easily possible? Would I have to write my own Semaphore? I assume that would be pretty advanced? Thanks, Steve

    Read the article

  • WCF - AsyncPattern=true or IsOneWay=true

    - by inutan
    Hello there, Few methods in my WCF service are quite time taking - Generating Reports and Sending E-mails. According to current requirement, it is required so that Client application just submits the request and then do not wait for the whole process to complete. It will allow user to continue doing other operations in client applications instead of waiting for the whole process to finish. I am in a doubt over which way to go: AsyncPattern = true OR IsOneWay=true Please guide.

    Read the article

  • Async trigger for an update panel refreshes entire page when triggering too much in too short of tim

    - by Matt
    I have a search button tied to an update panel as a trigger like so: <asp:Panel ID="CRM_Search" runat="server"> <p>Search:&nbsp;<asp:TextBox ID="CRM_Search_Box" CssClass="CRM_Search_Box" runat="server"></asp:TextBox> <asp:Button ID="CRM_Search_Button" CssClass="CRM_Search_Button" runat="server" Text="Search" OnClick="SearchLeads" /></p> </asp:Panel> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <Triggers> <asp:AsyncPostBackTrigger ControlID="CRM_Search_Button" /> </Triggers> <ContentTemplate> /* Content Here */ </ContentTemplate> </asp:UpdatePanel> In my javascript I use jQuery to grab the search box and tie it's keyup to make the search button click: $($(".CRM_Search_Box")[0]).keyup( function () { $($(".CRM_Search_Button")[0]).click(); } ); This works perfectly, except when I start typing too fast. As soon as I type too fast (my guess is if it's any faster than the data actually returns) the entire page refreshes (doing a postback?) instead of just the update panel. I've also found that instead of typing, if I just click the button really fast it starts doing the same thing. Is there any way to prevent it from doing this? Possibly prevent 2nd requests until the first has been completed? If I'm not on the right track then anyone have any other ideas? Thanks, Matt

    Read the article

  • Problems doing asynch operations in C# using Mutex.

    - by firoso
    I've tried this MANY ways, here is the current iteration. I think I've just implemented this all wrong. What I'm trying to accomplish is to treat this Asynch result in such a way that until it returns AND I finish with my add-thumbnail call, I will not request another call to imageProvider.BeginGetImage. To Clarify, my question is two-fold. Why does what I'm doing never seem to halt at my Mutex.WaitOne() call, and what is the proper way to handle this scenario? /// <summary> /// re-creates a list of thumbnails from a list of TreeElementViewModels (directories) /// </summary> /// <param name="list">the list of TreeElementViewModels to process</param> public void BeginLayout(List<AiTreeElementViewModel> list) { // *removed code for canceling and cleanup from previous calls* // Starts the processing of all folders in parallel. Task.Factory.StartNew(() => { thumbnailRequests = Parallel.ForEach<AiTreeElementViewModel>(list, options, ProcessFolder); }); } /// <summary> /// Processes a folder for all of it's image paths and loads them from disk. /// </summary> /// <param name="element">the tree element to process</param> private void ProcessFolder(AiTreeElementViewModel element) { try { var images = ImageCrawler.GetImagePaths(element.Path); AsyncCallback callback = AddThumbnail; foreach (var image in images) { Console.WriteLine("Attempting Enter"); synchMutex.WaitOne(); Console.WriteLine("Entered"); var result = imageProvider.BeginGetImage(callback, image); } } catch (Exception exc) { Console.WriteLine(exc.ToString()); // TODO: Do Something here. } } /// <summary> /// Adds a thumbnail to the Browser /// </summary> /// <param name="result">an async result used for retrieving state data from the load task.</param> private void AddThumbnail(IAsyncResult result) { lock (Thumbnails) { try { Stream image = imageProvider.EndGetImage(result); string filename = imageProvider.GetImageName(result); string imagePath = imageProvider.GetImagePath(result); var imageviewmodel = new AiImageThumbnailViewModel(image, filename, imagePath); thumbnailHash[imagePath] = imageviewmodel; HostInvoke(() => Thumbnails.Add(imageviewmodel)); UpdateChildZoom(); //synchMutex.ReleaseMutex(); Console.WriteLine("Exited"); } catch (Exception exc) { Console.WriteLine(exc.ToString()); // TODO: Do Something here. } } }

    Read the article

  • cancel stream request from WCF server to client

    - by ArsenMkrt
    Hi, I posted about stream request here [wcf-chunk-data-with-stream]:http://stackoverflow.com/questions/853448/wcf-chunk-data-with-stream I solved that task but now when i close request in client part server continue to send data. is it possible to cancel stream request from WCF server to client?

    Read the article

  • Why doesnt the AsyncCallback update my gridview?

    - by Naruji
    Hi all, I started working with delegates last week and i am trying to update my gridview async on the background. All goes well, no errors or such but i dont get a result after my EndInvoke. does anyone know what i am doing wrong? Here is a code snippet: public delegate string WebServiceDelegate(DataKey key); protected void btnCheckAll_Click(object sender, EventArgs e) { foreach (DataKey key in gvTest.DataKeys) { WebServiceDelegate wsDelegate = new WebServiceDelegate(GetWebserviceStatus); wsDelegate.BeginInvoke(key, new AsyncCallback(UpdateWebserviceStatus), wsDelegate); } } public string GetWebserviceStatus(DataKey key) { return String.Format("Updated {0}", key.Value); } public void UpdateWebserviceStatus(IAsyncResult result) { WebServiceDelegate wsDelegate = (WebServiceDelegate)result.AsyncState; Label lblUpdate = (Label)gvTest.Rows[Convert.ToInt32(key.Value)].FindControl("lblUpdate"); lblUpdate.Text = wsDelegate.EndInvoke(result); }

    Read the article

  • C# Begin/EndReceive - how do I read large data?

    - by ryeguy
    When reading data in chunks of say, 1024, how do I continue to read from a socket that receives a message bigger than 1024 bytes until there is no data left? Should I just use BeginReceive to read a packet's length prefix only, and then once that is retrieved, use Receive() (in the async thread) to read the rest of the packet? Or is there another way? edit: I thought Jon Skeet's link had the solution, but there is a bit of a speedbump with that code. The code I used is: public class StateObject { public Socket workSocket = null; public const int BUFFER_SIZE = 1024; public byte[] buffer = new byte[BUFFER_SIZE]; public StringBuilder sb = new StringBuilder(); } public static void Read_Callback(IAsyncResult ar) { StateObject so = (StateObject) ar.AsyncState; Socket s = so.workSocket; int read = s.EndReceive(ar); if (read > 0) { so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read)); if (read == StateObject.BUFFER_SIZE) { s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0, new AyncCallback(Async_Send_Receive.Read_Callback), so); return; } } if (so.sb.Length > 0) { //All of the data has been read, so displays it to the console string strContent; strContent = so.sb.ToString(); Console.WriteLine(String.Format("Read {0} byte from socket" + "data = {1} ", strContent.Length, strContent)); } s.Close(); } Now this corrected works fine most of the time, but it fails when the packet's size is a multiple of the buffer. The reason for this is if the buffer gets filled on a read it is assumed there is more data; but the same problem happens as before. A 2 byte buffer, for exmaple, gets filled twice on a 4 byte packet, and assumes there is more data. It then blocks because there is nothing left to read. The problem is that the receive function doesn't know when the end of the packet is. This got me thinking to two possible solutions: I could either have an end-of-packet delimiter or I could read the packet header to find the length and then receive exactly that amount (as I originally suggested). There's problems with each of these, though. I don't like the idea of using a delimiter, as a user could somehow work that into a packet in an input string from the app and screw it up. It also just seems kinda sloppy to me. The length header sounds ok, but I'm planning on using protocol buffers - I don't know the format of the data. Is there a length header? How many bytes is it? Would this be something I implement myself? Etc.. What should I do?

    Read the article

  • How to download images in playframework jobs?

    - by MrROY
    I have a playframework Job class like this: public class ImageDownloader extends Job { private String[] urls; private String dir; public ImageDownloader(){} public ImageDownloader(String[] urls,String dir){ this.urls = urls; this.dir = dir; } @Override public void doJob() throws Exception { if(urls!=null && urls.length > 0){ for (int i = 0; i < urls.length; i++) { String url = urls[i]; //Dowloading } } } } Play(1.2.4) has lots of amazing tools to make things easy. So i wonder whether there's a way to make the downloading easy and beautiful in play ?

    Read the article

  • Async actions inside Silverlight Method - returning the value

    - by tyndall
    What is the proper way to call an Async framework component - wait for an answer and then return the value. AKA contain the entire request/response in a single method. Example code: public class Experiment { public Experiment() { } public string GetSomeString() { WebClient wc = new WebClient(); wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); Uri u = new Uri("http://news.google.com/news?pz=1&cf=all&ned=us&hl=en&topic=t&output=rss"); wc.DownloadStringAsync(u); return "the news RSS from Google"; } private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { //don't really see how this callback method makes it able // to return the answer I'm looking for on the return // statement in the method above. } } MORE INFO: The reason I'm asking this that I have a project I'm working on where I'd like JavaScript code in the browser to use Silverlight like a Facade/Proxy to Web services and complex calculations & operations. I'd like to make the calls to the [ScriptableMembers] in Silvelight synchronously. I don't want Silverlight to callback into the browser's JavaScript

    Read the article

  • jQuery Ajax / .each callback, next 'each' firing before ajax completed

    - by StuR
    Hi the below Javascript is called when I submit a form. It first splits a bunch of url's from a text area, it then: 1) Adds lines to a table for each url, and in the last column (the 'status' column) it says "Not Started". 2) Again it loops through each url, first off it makes an ajax call to check on the status (status.php) which will return a percentage from 0 - 100. 3) In the same loop it kicks off the actual process via ajax (process.php), when the process has completed (bearing in the mind the continuous status updates), it will then say "Completed" in the status column and exit the auto_refresh. 4) It should then go to the next 'each' and do the same for the next url. function formSubmit(){ var lines = $('#urls').val().split('\n'); $.each(lines, function(key, value) { $('#dlTable tr:last').after('<tr><td>'+value+'</td><td>Not Started</td></tr>'); }); $.each(lines, function(key, value) { var auto_refresh = setInterval( function () { $.ajax({ url: 'status.php', success: function(data) { $('#dlTable').find("tr").eq(key+1).children().last().replaceWith("<td>"+data+"</td>"); } }); }, 1000); $.ajax({ url: 'process.php?id='+value, success: function(msg) { clearInterval(auto_refresh); $('#dlTable').find("tr").eq(key+1).children().last().replaceWith("<td>completed rip</td>"); } }); }); }

    Read the article

  • How to implement a bidirectional "mailbox service" over tcp?

    - by igorgatis
    The idea is to allow to peer processes to exchange messages (packets) over tcp as much asynchronously as possible. The way I'd like it to work is each process to have an outbox and an inbox. The send operation is just a push on the outbox. The receive operation is just a pop on the inbox. Underlying protocol would take care of the communication details. Is there a way to implement such mechanism using a single TCP connection? How would that be implemented using BSD sockets and modern OO Socket APIs (like Java or C# socket API)?

    Read the article

  • Passing methods/functions as args in Objective C

    - by Baishampayan Ghose
    Hello, I am new to Objective C and I am trying to implement an async library which works with callbacks. I need to figure out a way to pass callback methods as args to my async methods so that the callback can be invoked when the task is finished. What is the best way to achieve this in Objective C? In Python, for example I could easily pass a function, but in Objective C it seems selectors are the way to go(?). Can anyone point me to an example from where I can get some ideas? Thanks in advance.

    Read the article

  • Implementing a robust async stream reader

    - 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, but that is a detail and does not play an important role. 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. 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

  • Control.EndInvoke resets call stack for exception

    - by Brian Rasmussen
    I don't do a lot of Windows GUI programming, so this may all be common knowledge to people more familiar with WinForms than I am. Unfortunately I have not been able to find any resources to explain the issue, I encountered today during debugging. If we call EndInvoke on an async delegate. We will get any exception thrown during execution of the method re-thrown. The call stack will reflect the original source of the exception. However, if we do something similar on a Windows.Forms.Control, the implementation of Control.EndInvoke resets the call stack. This can be observed by a simple test or by looking at the code in Reflector. The relevant code excerpt from EndInvoke is here: if (entry.exception != null) { throw entry.exception; } I understand that Begin/EndInvoke on Control and async delegates are different, but I would have expected similar behavior on Control.EndInvoke. Is there any reason Control doesn't do whatever it is async delegates do to preserve the original call stack?

    Read the article

  • problem in silverlight 4 async how to wait till result come

    - by AQEEL
    Here is what i have problem i have following code : //Get All master record entryE_QuestMaster = new ObservableCollection<E_QuestMaster>(); QuestVM.getExamsMasterbyExamID(eUtility.ConvertInt32(this.txtID.Text), ref entryE_QuestMaster); // //Loop to show questions int iNumber=1; foreach (var oIn in entryE_QuestMaster) { Node subNode = new Node(); subNode.Content = oIn.e_Question; subNode.Name = "Quest_" + iNumber.ToString().Trim(); subNode.Tag = oIn.e_QID.ToString(); subNode.Icon = "/Images/Number/" + iNumber.ToString().Trim() + ".gif"; iNumber++; this.tvMainNode.Nodes.Add(subNode); } here is async method calling wcf service /// <summary> /// /// </summary> /// <param name="ID"></param> public void getExamsMasterbyExamID(int ID, ref ObservableCollection<E_QuestMaster> iCollectionData) { ObservableCollection<E_QuestMaster> iCollectionDataResult = iCollectionData; eLearningDataServiceClient client = new eLearningDataServiceClient(); client.getExamsMasterCompleted+=(s,e)=> { iCollectionDataResult = e.Result; }; client.getExamsMasterAsync(ID); } problem : when ever system run -- QuestVM.getExamsMasterbyExamID(eUtility.ConvertInt32(this.txtID.Text), ref entryE_QuestMaster); its does not wait till i get e.result its just move to next line of code which is foreach loop. plssss help any one or give idea with sample code what should i do to wait till e.result i wanted to some how wait till i get e.result any idea ?

    Read the article

  • How to load an ajax (jquery) request response progressively without waiting for it to finish?

    - by Sebastian
    I want to make a form that will use jquery to submit a list of keyword to a php file, this file could take a lot of time to load depending on the size of the keywords list. What I want to do is to load the php response into a div or container in real time without using iframes. All the ajax request I know have to wait until the request has finished before having access to the response, I need to get access to that response even when it hasn't finished so I can update the progress in real time.

    Read the article

  • Cannot await 'Model.PersonalInfo'

    - by Gooftroop
    I have the following method in a DesignDataService class public async Task<T> GetData<T>(T dataObject) { var typeName = typeof(T).Name; switch (typeName) { case "PersonalInfo": var person = new PersonalInfo { FirstName = "Mickey", LastName = "Mouse" , Adres = new Address{Country="DLRP"} , }; return await person; } // end Switch } // GetData<T> How can I return a new PersonalInfo class from the DataService? For now I get the error Cannot await 'Model.PersonalInfo' Even when I change the return statement as follows return await person as Task; the error stays the same Thanks in advanced Danny

    Read the article

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