Search Results

Search found 7175 results on 287 pages for 'asynchronous processing'.

Page 4/287 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Asynchronous Silverlight WCF callback

    - by Matt
    I've created my own WCF service and I've successfully been able to talk to it via my Silverlight client. I ran into an interesting problem on my asynchronous callbacks though. When my callback is invoked, I can't update any UI controls with the dreaded invalid cross thread access Here's what my callback function looks like private void GetTimeCallBack( object sender, Talk.ClientBase<IService>.ClientEventArgs e ) { lblDisplay.Text = e.Object.ToString(); } A quick google search showed me that I have to do this instead. private void GetTimeCallBack( object sender, Talk.ClientBase<IService>.ClientEventArgs e ) { Dispatcher.BeginInvoke( () => lblDisplay.Text = e.Object.ToString() ); } Now everything works fine, but I wasn't expecting my callback to be running on a different thread. Will I always have to use the Dispatcher class in order to modify anything within my class or is this just limited to UI elements? I've not familiar with the Dispatcher class at all so I'm looking to understand it more.

    Read the article

  • Asynchronous Sockets - Handling false socket.AcceptAsync values

    - by David
    The Socket class has a method .AcceptAsync which either returns true or false. I'd thought the false return value was an error condition, but in the samples Microsoft provide for Async sockets they call the callback function synchronously after checking for failure, as shown here: public void StartAccept(SocketAsyncEventArgs acceptEventArg) { if (acceptEventArg == null) { acceptEventArg = new SocketAsyncEventArgs(); acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed); } else { // socket must be cleared since the context object is being reused acceptEventArg.AcceptSocket = null; } m_maxNumberAcceptedClients.WaitOne(); bool willRaiseEvent = listenSocket.AcceptAsync(acceptEventArg); if (!willRaiseEvent) { ProcessAccept(acceptEventArg); } } /// <summary> /// This method is the callback method associated with Socket.AcceptAsync operations and is invoked /// when an accept operation is complete /// </summary> void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs e) { ProcessAccept(e); } Why do they do this? It defeats the purpose of asynchronous sockets and stops the method from returning.

    Read the article

  • ASP.NET Asynchronous Tasks - Worker Thread Not Releasing?

    - by user296752
    I am having an issue with testing asynchronous tasks in ASP.NET & IIS7. From what I have read, the worker thread should be released back into the thread pool while the I/O thread performs the async work, allowing ASP.NET to server other incoming requests. But when I simulate heavy load on the web application by making 20 simultaneous requests to a page (async.aspx) that performs long running async tasks, I am unable to browse to some other normal aspx page until the requests are just about done. Am I misunderstanding or missing something here? I am running Vista Biz x64, VS2008 + IIS7. I have the Async attribute applied to the Page directive.

    Read the article

  • Javascript ajax asynchronous question...

    - by Polaris878
    Hello, I'm wondering if anyone can help me understand some asynchronous javascript concepts... Say I make an asynch ajax call like so: xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange= myFoo; xmlhttp.open("GET",url,true); Here is my callback function: function myFoo() { if (xmlhttp.readyState==4) { if (xmlhttp.status==200) { // Success message } else { // some error message } } } Now, where and when does the execution path start again? Once I make the call to open(), does execution continue directly below the open() and another "thread" enters the asynch function once the ajax request has been completed? Or, does the browser wait for the request to complete, make the Asynch call, and then execution continues right after the open? Thanks!

    Read the article

  • javascript: execute a bunch of asynchronous method with one callback

    - by Samuel Michelot
    I need to execute a bunch of asynchronous methods (client SQLite database), and call only one final callback. Of course, the ugly way is: execAll : function(callBack) { asynch1(function() { asynch2(function() { ... asynchN(function() { callBack(); }) }) }); } But I know there are better ways to do it. Intuitively I would detect when all call back has been called with a counter to call the final callback. I think this is a common design-pattern, so if someone could point me in the right direction... Thanks in advance !

    Read the article

  • Making an asynchronous interface appear synchronous to mod_python users

    - by Trey
    I have a Python-driven web interface powered by Apache 2.2 with mod_python and Python 2.4. I need to make an asynchronous process appear synchronous to users of this web interface. When users access one module on this website: An external SOAP interface will be contacted with a unique identifier and will respond with a number N The external interface will respond asynchronously by contacting a SOAP server on my machine between 1 and 10 times (the number N tells us how many responses we will receive) I need to somehow aggregate these responses and pass them to the original module which will display the information back to the user. The goal is to make the process appear synchronous to the user. What is the best way to handle this synchronization issue? Is this something Twisted would be well-suited for? I am not restricting myself to Python for the solution, though it is preferred because everything else on the server is in Python. I prefer a solution that is both scalable and will take a minimal amount of programming time (though I understand that these attributes are somewhat at odds).

    Read the article

  • Dowloading a bunch of files asynchronous wait till last finished

    - by Casper Broeren
    I'm trying to download a lot of files after downloading a sql statement must insert a record. I'm using System.Net.Client to download each file synchronously, still it could be done asynchronous. There's no relation or dependency between each download. At first I just tried to use WebClient.DownloadFileAsync but that shutted the program down and killed all the download processes/threads. Second I tried to create a wait routine something like this; while (processedFiles < totalFiles) Thread.Sleep(1000) This freezed everything. So could someone tell me which aproach to take to implement this Async?

    Read the article

  • C# Asynchronous Sockets questions.

    - by ccppjava
    Based on my reading and testing, with asynchronous sockets, the socket itself can be passed using state object (IAsyncResult result), also if store the socket as a private field, it would be captured by the callback methods. I am wondering how the IAysnResult is kepted between the BeginXXX and ReceiveXXX? It looks to me that after the BeginXXX call and the method ends, the state object would be disposed by GC if there is no reference to it. In the case of private field, how the private field is shared between threads? (As far as I know, a callback is executed using a thread from the default thread pool, which would be considered as a new thread.) Many thanks, hope the questions themselves are clear.

    Read the article

  • High performance distributed asynchronous RPC in java

    - by unludo
    I would like to do RPC to a list of clients with the following requirements: the server does not know the clients (implies a kind of broker?) and the cleints do not know the server there may be several clients - they share the load to treat the RPC The RPC is asynchronous very fast (round-trip < 1ms) optional : offers a fail-over mechanism. It can be done with underlying tools which are not really intended for that (Hazelcast is an example). What would you use for such requirements? Thanks!

    Read the article

  • Python - How can I make this code asynchronous?

    - by dave
    Here's some code that illustrates my problem: def blocking1(): while True: yield 'first blocking function example' def blocking2(): while True: yield 'second blocking function example' for i in blocking1(): print 'this will be shown' for i in blocking2(): print 'this will not be shown' I have two functions which contain while True loops. These will yield data which I will then log somewhere (most likely, to an sqlite database). I've been playing around with threading and have gotten it working. However, I don't really like it... What I would like to do is make my blocking functions asynchronous. Something like: def blocking1(callback): while True: callback('first blocking function example') def blocking2(callback): while True: callback('second blocking function example') def log(data): print data blocking1(log) blocking2(log) How can I achieve this in Python? I've seen the standard library comes with asyncore and the big name in this game is Twisted but both of these seem to be used for socket IO. How can I async my non-socket related, blocking functions?

    Read the article

  • Photoshop batch image processing based on EXIF?

    - by davr
    I use Photoshop to batch convert my RAW files to JPG. I was wondering if there was a way to make it take different actions based on EXIF? With my particular camera lens, if I open it all the way to F1.7 there is noticeable vignetting, but stopping down smaller doesn't have that problem. What I'd like to do is have Photoshop batch process all my RAW files, and anything that is at F1.7 it should automatically apply vignette correction, but not on the others (applying correction to the others would over-brighten the corners of the image). Is anything like this possible? Should I use some other RAW processing tool instead? FYI they are RW2 files from a Panasonic GF1 camera.

    Read the article

  • Ideas on frameworks in .NET that can be used for job processing and notifications

    - by Rajat Mehta
    Scenario: We have one instance of WCF windows service which exposes contracts like: AddNewJob(Job job), GetJobs(JobQuery query) etc. This service is consumed by 70-100 instances of client which is Windows Form based .NET app. Typically the service has 50-100 inward calls/minute to add or query jobs that are stored in a table on Sql Server. The same service is also responsible for processing these jobs in real time. It queries database every 5 seconds picks up the queued jobs and starts processing them. A job has 6 states. Queued, Pre-processing, Processing, Post-processing, Completed, Failed, Locked. Another responsibility on this service is to update all clients on every state change of every job. This means almost 200+ callbacks to clients per second. Question: This whole implementation is done using WCF Duplex bindings and works perfectly fine on small number of parallel jobs. Problem arises when we scale it up to 1000 jobs at a time. The notifications don't work as expected, it leads to memory overflow etc. Is there any standard framework that can provide a clean infrastructure for handling this scenario?? Apologies for the long explanation!

    Read the article

  • Multiple asynchronous method calls to method while in a loop

    - by ranabra
    I have spent a whole day trying various ways using 'AddOnPreRenderCompleteAsync' and 'RegisterAsyncTask' but no success so far. I succeeded making the call to the DB asynchronous using 'BeginExecuteReader' and 'EndExecuteReader' but that is missing the point. The asynch handling should not be the call to the DB which in my case is fast, it should be afterwards, during the 'while' loop, while calling an external web-service. I think the simplified pseudo code will explain best: (Note: the connection string is using 'MultipleActiveResultSets') "Select ID, UserName from MyTable" 'Open connection to DB ExecuteReader(); if (DR.HasRows) {     while (DR.Read())     {         'Call external web-service         'and get current Temperature of each UserName - DR["UserName"].ToString()         'Update my local DB         Update MyTable set Temperature = ValueFromWebService where UserName =                                       DR["UserName"]         CmdUpdate.ExecuteNonQuery();     }     'Close connection etc } Accessing the DB is fast. Getting the returned result from the external web-service is slow and that at least should be handled Asynchnously. If each call to the web service takes just 1 second, assuming I have only 100 users it will take minimum 100 seconds for the DB update to complete, which obviously is not an option. There eventually should be thousands of users (currently only 2). Currently everything works, just very synchnously :) Thoughts to myself: Maybe my way of approaching this is wrong? Maybe the entire process should be called Asynchnously Many thanx

    Read the article

  • Dealing with asynchronous control structures (Fluent Interface?)

    - by Christophe Herreman
    The initialization code of our Flex application is doing a series of asynchronous calls to check user credentials, load external data, connecting to a JMS topic, etc. Depending on the context the application runs in, some of these calls are not executed or executed with different parameters. Since all of these calls happen asynchronously, the code controlling them is hard to read, understand, maintain and test. For each call, we need to have some callback mechanism in which we decide what call to execute next. I was wondering if anyone had experimented with wrapping these calls in executable units and having a Fluent Interface (FI) that would connect and control them. From the top of my head, the code might look something like: var asyncChain:AsyncChain = execute(LoadSystemSettings) .execute(LoadAppContext) .if(IsAutologin) .execute(AutoLogin) .else() .execute(ShowLoginScreen) .etc; asyncChain.execute(); The AsyncChain would be an execution tree, build with the FI (and we could of course also build one without a FI). This might be an interesting idea for environments that run in a single threaded model like the Flash Player, Silverlight, JavaFX?, ... Before I dive into the code to try things out, I was hoping to get some feedback.

    Read the article

  • Asynchronous background processes in Python?

    - by Geuis
    I have been using this as a reference, but not able to accomplish exactly what I need: http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python/92395#92395 I also was reading this: http://www.python.org/dev/peps/pep-3145/ For our project, we have 5 svn checkouts that need to update before we can deploy our application. In my dev environment, where speedy deployments are a bit more important for productivity than a production deployment, I have been working on speeding up the process. I have a bash script that has been working decently but has some limitations. I fire up multiple 'svn updates' with the following bash command: (svn update /repo1) & (svn update /repo2) & (svn update /repo3) & These all run in parallel and it works pretty well. I also use this pattern in the rest of the build script for firing off each ant build, then moving the wars to Tomcat. However, I have no control over stopping deployment if one of the updates or a build fails. I'm re-writing my bash script with Python so I have more control over branches and the deployment process. I am using subprocess.call() to fire off the 'svn update /repo' commands, but each one is acting sequentially. I try '(svn update /repo) &' and those all fire off, but the result code returns immediately. So I have no way to determine if a particular command fails or not in the asynchronous mode. import subprocess subprocess.call( 'svn update /repo1', shell=True ) subprocess.call( 'svn update /repo2', shell=True ) subprocess.call( 'svn update /repo3', shell=True ) I'd love to find a way to have Python fire off each Unix command, and if any of the calls fails at any time the entire script stops.

    Read the article

  • Asynchronous event loop design and issues.

    - by Artyom
    Hello, I'm designing event loop for asynchronous socket IO using epoll/devpoll/kqueue/poll/select (including windows-select). I have two options of performing, IO operation: Non-blocking mode, poll on EAGAIN Set socket to non-blocking mode. Read/Write to socket. If operation succeeds, post completion notification to event loop. If I get EAGAIN, add socket to "select list" and poll socket. Polling mode: poll and then execute Add socket to select list and poll it. Wait for notification that it is readable writable read/write Post completion notification to event loop of sucseeds To me it looks like first would require less system calls when using in normal mode, especially for writing to socket (buffers are quite big). Also it looks like that it would be possible to reduce the overhead over number of "select" executions, especially it is nice when you do not have something that scales well as epoll/devpoll/kqueue. Questions: Are there any advantages of the second approach? Are there any portability issues with non-blocking operations on sockets/file descriptors over numerous operating systems: Linux, FreeBSD, Solaris, MacOSX, Windows. Notes: Please do not suggest using existing event-loop/socket-api implementations

    Read the article

  • Blackberry Asynchronous HTTP Requests - How?

    - by Kai
    The app I'm working on has a self contained database. The only time I need HTTP request is when the user first loads the app. I do this by calling a class that verifies whether or not a local DB exists and, if not, create one with the following request: HttpRequest data = new HttpRequest("http://www.somedomain.com/xml", "GET", this); data.start(); This xml returns a list of content, all of which have images that I want to fetch AFTER the original request is complete and stored. So something like this won't work: HttpRequest data = new HttpRequest("http://www.somedomain.com/xml", "GET", this); data.start(); HttpRequest images = new HttpRequest("http://www.somedomain.com/xmlImages", "GET", this); images.start(); Since it will not treat this like an asynchronous request. I have not found much information on adding callbacks to httpRequest, or any other method I could use to ensure operation 2 does not execute until operation 1 is complete. Any help would be appreciated. Thanks

    Read the article

  • Sequential access to asynchronous sockets

    - by Lars A. Brekken
    I have a server that has several clients C1...Cn to each of which there is a TCP connection established. There are less than 10,000 clients. The message protocol is request/response based, where the server sends a request to a client and then the client sends a response. The server has several threads, T1...Tm, and each of these may send requests to any of the clients. I want to make sure that only one of these threads can send a request to a specific client at any one time, while the other threads wanting to send a request to the same client will have to wait. I do not want to block threads from sending requests to different clients at the same time. E.g. If T1 is sending a request to C3, another thread T2 should not be able to send anything to C3 until T1 has received its response. I was thinking of using a simple lock statement on the socket: lock (c3Socket) { // Send request to C3 // Get response from C3 } I am using asynchronous sockets, so I may have to use Monitor instead: Monitor.Enter(c3Socket); // Before calling .BeginReceive() And Monitor.Exit(c3Socket); // In .EndReceive I am worried about stuff going wrong and not letting go of the monitor and therefore blocking all access to a client. I'm thinking that my heartbeat thread could use Monitor.TryEnter() with a timeout and throw out sockets that it cannot get the monitor for. Would it make sense for me to make the Begin and End calls synchronous in order to be able to use the lock() statement? I know that I would be sacrificing concurrency for simplicity in this case, but it may be worth it. Am I overlooking anything here? Any input appreciated.

    Read the article

  • how to use q.js promises to work with multiple asynchronous operations

    - by kimsia
    Note: This question is also cross-posted in Q.js mailing list over here. i had a situation with multiple asynchronous operations and the answer I accepted pointed out that using Promises using a library such as q.js would be more beneficial. I am convinced to refactor my code to use Promises but because the code is pretty long, i have trimmed the irrelevant portions and exported the crucial parts into a separate repo. The repo is here and the most important file is this. The requirement is that I want pageSizes to be non-empty after traversing all the dragged'n dropped files. The problem is that the FileAPI operations inside getSizeSettingsFromPage function causes getSizeSettingsFromPage to be async. So I cannot place checkWhenReady(); like this. function traverseFiles() { for (var i=0, l=pages.length; i<l; i++) { getSizeSettingsFromPage(pages[i], calculateRatio); } checkWhenReady(); // this always returns 0. } This works, but it is not ideal. I prefer to call checkWhenReady just ONCE after all the pages have undergone this function calculateRatio successfully. function calculateRatio(width, height, filename) { // .... code pageSizes.add(filename, object); checkWhenReady(); // this works but it is not ideal. I prefer to call this method AFTER all the `pages` have undergone calculateRatio // ..... more code... } How do I refactor the code to make use of Promises in Q.js?

    Read the article

  • Asynchronous callback for network in Objective-C Iphone

    - by vodkhang
    I am working with network request - response in Objective-C. There is something with asynchronous model that I don't understand. In summary, I have a view that will show my statuses from 2 social networks: Twitter and Facebook. When I clicked refresh, it will call a model manager. That model manager will call 2 service helpers to request for latest items. When 2 service helpers receive data, it will pass back to model manager and this model will add all data into a sorted array. What I don't understand here is that : when response from social networks come back, how many threads will handle the response. From my understanding about multithreading and networking (in Java), there must have 2 threads handle 2 responses and those 2 threads will execute the code to add the responses to the array. So, it can have race condition and the program can go wrong right? Is it the correct working model of iphone objective-C? Or they do it in a different way that it will never have race condition and we don't have to care about locking, synchronize? Here is my example code: ModelManager.m - (void)updateMyItems:(NSArray *)items { self.helpers = [self authenticatedHelpersForAction:NCHelperActionGetMyItems]; for (id<NCHelper> helper in self.helpers) { [helper updateMyItems:items]; // NETWORK request here } } - (void)helper:(id <NCHelper>)helper didReturnItems:(NSArray *)items { [self helperDidFinishGettingMyItems:items callback:@selector(model:didGetMyItems:)]; break; } } // some private attributes int *_currentSocialNetworkItemsCount = 0; // to count the number of items of a social network - (void)helperDidFinishGettingMyItems:(NSArray *)items { for (Item *item in items) { _currentSocialNetworkItemsCount ++; } NSLog(@"count: %d", _currentSocialNetworkItemsCount); _currentSocialNetworkItemsCount = 0; } I want to ask if there is a case that the method helperDidFinishGettingMyItems is called concurrently. That means, for example, faceboook returns 10 items, twitter returns 10 items, will the output of count will ever be larger than 10? And if there is only one single thread, how can the thread finishes parsing 1 response and jump to the other response because, IMO, thread is only executed sequently, block of code by block of code

    Read the article

  • Asynchronous subprocess on Windows

    - by Stigma
    First of all, the overall problem I am solving is a bit more complicated than I am showing here, so please do not tell me 'use threads with blocking' as it would not solve my actual situation without a fair, FAIR bit of rewriting and refactoring. I have several applications which are not mine to modify, which take data from stdin and poop it out on stdout after doing their magic. My task is to chain several of these programs. Problem is, sometimes they choke, and as such I need to track their progress which is outputted on STDERR. pA = subprocess.Popen(CommandA, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # ... some more processes make up the chain, but that is irrelevant to the problem pB = subprocess.Popen(CommandB, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=pA.stdout ) Now, reading directly through pA.stdout.readline() and pB.stdout.readline(), or the plain read() functions, is a blocking matter. Since different applications output in different paces and different formats, blocking is not an option. (And as I wrote above, threading is not an option unless at a last, last resort.) pA.communicate() is deadlock safe, but since I need the information live, that is not an option either. Thus google brought me to this asynchronous subprocess snippet on ActiveState. All good at first, until I implement it. Comparing the cmd.exe output of pA.exe | pB.exe, ignoring the fact both output to the same window making for a mess, I see very instantaneous updates. However, I implement the same thing using the above snippet and the read_some() function declared there, and it takes over 10 seconds to notify updates of a single pipe. But when it does, it has updates leading all the way upto 40% progress, for example. Thus I do some more research, and see numerous subjects concerning PeekNamedPipe, anonymous handles, and returning 0 bytes available even though there is information available in the pipe. As the subject has proven quite a bit beyond my expertise to fix or code around, I come to Stack Overflow to look for guidance. :) My platform is W7 64-bit with Python 2.6, the applications are 32-bit in case it matters, and compatibility with Unix is not a concern. I can even deal with a full ctypes or pywin32 solution that subverts subprocess entirely if it is the only solution, as long as I can read from every stderr pipe asynchronously with immediate performance and no deadlocks. :)

    Read the article

  • Odd performance with C# Asynchronous server socket

    - by The.Anti.9
    I'm working on a web server in C# and I have it running on Asynchronous socket calls. The weird thing is that for some reason, when you start loading pages, the 3rd request is where the browser won't connect. It just keeps saying "Connecting..." and doesn't ever stop. If I hit stop. and then refresh, it will load again, but if I try another time after that it does the thing where it doesn't load again. And it continues in that cycle. I'm not really sure what is making it do that. The code is kind of hacked together from a couple of examples and some old code I had. Any miscellaneous tips would be helpful as well. Heres my little Listener class that handles everything (pastied here. thought it might be easier to read this way) using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace irek.Server { public class Listener { private int port; private Socket server; private Byte[] data = new Byte[2048]; static ManualResetEvent allDone = new ManualResetEvent(false); public Listener(int _port) { port = _port; } public void Run() { server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, port); server.Bind(iep); Console.WriteLine("Server Initialized."); server.Listen(5); Console.WriteLine("Listening..."); while (true) { allDone.Reset(); server.BeginAccept(new AsyncCallback(AcceptCon), server); allDone.WaitOne(); } } private void AcceptCon(IAsyncResult iar) { allDone.Set(); Socket s = (Socket)iar.AsyncState; Socket s2 = s.EndAccept(iar); SocketStateObject state = new SocketStateObject(); state.workSocket = s2; s2.BeginReceive(state.buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new AsyncCallback(Read), state); } private void Read(IAsyncResult iar) { try { SocketStateObject state = (SocketStateObject)iar.AsyncState; Socket s = state.workSocket; int read = s.EndReceive(iar); if (read > 0) { state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, read)); if (s.Available > 0) { s.BeginReceive(state.buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new AsyncCallback(Read), state); return; } } if (state.sb.Length > 1) { string requestString = state.sb.ToString(); // HANDLE REQUEST HERE // Temporary response string resp = "<h1>It Works!</h1>"; string head = "HTTP/1.1 200 OK\r\nContent-Type: text/html;\r\nServer: irek\r\nContent-Length:"+resp.Length+"\r\n\r\n"; byte[] answer = Encoding.ASCII.GetBytes(head+resp); // end temp. state.workSocket.BeginSend(answer, 0, answer.Length, SocketFlags.None, new AsyncCallback(Send), state.workSocket); } } catch (Exception) { return; } } private void Send(IAsyncResult iar) { try { SocketStateObject state = (SocketStateObject)iar.AsyncState; int sent = state.workSocket.EndSend(iar); state.workSocket.Shutdown(SocketShutdown.Both); state.workSocket.Close(); } catch (Exception) { } return; } } } And my SocketStateObject: public class SocketStateObject { public Socket workSocket = null; public const int BUFFER_SIZE = 1024; public byte[] buffer = new byte[BUFFER_SIZE]; public StringBuilder sb = new StringBuilder(); }

    Read the article

  • C# Asynchronous Network IO and OutOfMemoryException

    - by The.Anti.9
    I'm working on a client/server application in C#, and I need to get Asynchronous sockets working so I can handle multiple connections at once. Technically it works the way it is now, but I get an OutOfMemoryException after about 3 minutes of running. MSDN says to use a WaitHandler to do WaitOne() after the socket.BeginAccept(), but it doesn't actually let me do that. When I try to do that in the code it says WaitHandler is an abstract class or interface, and I can't instantiate it. I thought maybe Id try a static reference, but it doesnt have teh WaitOne() method, just WaitAll() and WaitAny(). The main problem is that in the docs it doesn't give a full code snippet, so you can't actually see what their "wait handler" is coming from. its just a variable called allDone, which also has a Reset() method in the snippet, which a waithandler doesn't have. After digging around in their docs, I found some related thing about an AutoResetEvent in the Threading namespace. It has a WaitOne() and a Reset() method. So I tried that around the while(true) { ... socket.BeginAccept( ... ); ... }. Unfortunately this makes it only take one connection at a time. So I'm not really sure where to go. Here's my code: class ServerRunner { private Byte[] data = new Byte[2048]; private int size = 2048; private Socket server; static AutoResetEvent allDone = new AutoResetEvent(false); public ServerRunner() { server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 33333); server.Bind(iep); Console.WriteLine("Server initialized.."); } public void Run() { server.Listen(100); Console.WriteLine("Listening..."); while (true) { //allDone.Reset(); server.BeginAccept(new AsyncCallback(AcceptCon), server); //allDone.WaitOne(); } } void AcceptCon(IAsyncResult iar) { Socket oldserver = (Socket)iar.AsyncState; Socket client = oldserver.EndAccept(iar); Console.WriteLine(client.RemoteEndPoint.ToString() + " connected"); byte[] message = Encoding.ASCII.GetBytes("Welcome"); client.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(SendData), client); } void SendData(IAsyncResult iar) { Socket client = (Socket)iar.AsyncState; int sent = client.EndSend(iar); client.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), client); } void ReceiveData(IAsyncResult iar) { Socket client = (Socket)iar.AsyncState; int recv = client.EndReceive(iar); if (recv == 0) { client.Close(); server.BeginAccept(new AsyncCallback(AcceptCon), server); return; } string receivedData = Encoding.ASCII.GetString(data, 0, recv); //process received data here byte[] message2 = Encoding.ASCII.GetBytes("reply"); client.BeginSend(message2, 0, message2.Length, SocketFlags.None, new AsyncCallback(SendData), client); } }

    Read the article

  • When using delegates, need better way to do sequential processing

    - by Padawan
    I have a class WebServiceCaller that uses NSURLConnection to make asynchronous calls to a web service. The class provides a delegate property and when the web service call is done, it calls a method webServiceDoneWithXXX on the delegate. There are several web service methods that can be called, two of which are say GetSummary and GetList. The classes that use WebServiceCaller initially need both the summary and list so they are written like this: -(void)getAllData { [webServiceCaller getSummary]; } -(void)webServiceDoneWithGetSummary { [webServiceCaller getList]; } -(void)webServiceDoneWithGetList { ... } This works but there are at least two problems: The calls are split across delegate methods so it's hard to see the sequence at a glance but more important it's hard to control or modify the sequence. Sometimes I want to call just GetSummary and not also GetList so I would then have to use an ugly class-level state variable that tells webServiceDoneWithGetSummary whether to call GetList or not. Assume that GetList cannot be done until GetSummary completes and returns some data which is used as input to GetList. Is there a better way to handle this and still get asynchronous calls? Update based on Matt Long's answer: Using notifications instead of a delegate, it looks like I can solve problem #2 by setting a different selector depending on whether I want the full sequence (GetSummary+GetList) or just GetSummary. Both observers would still use the same notification name when calling GetSummary. I would have to write two separate methods to handle GetSummaryDone instead of using a single delegate method (where I would have needed some class-level variable to tell whether to then call GetList). -(void)getAllData { [[NSNotificationCenter defaultCenter] addObserver:self              selector:@selector(getSummaryDoneAndCallGetList:)                  name:kGetSummaryDidFinish object:nil];     [webServiceCaller getSummary]; } -(void)getSummaryDoneAndCallGetList { [NSNotificationCenter removeObserver] //process summary data [[NSNotificationCenter defaultCenter] addObserver:self              selector:@selector(getListDone:)                  name:kGetListDidFinish object:nil];     [webServiceCaller getList]; } -(void)getListDone { [NSNotificationCenter removeObserver] //process list data } -(void)getJustSummaryData { [[NSNotificationCenter defaultCenter] addObserver:self              selector:@selector(getJustSummaryDone:) //different selector but                  name:kGetSummaryDidFinish object:nil]; //same notification name     [webServiceCaller getSummary]; } -(void)getJustSummaryDone { [NSNotificationCenter removeObserver] //process summary data } I haven't actually tried this yet. It seems better than having state variables and if-then statements but you have to write more methods. I still don't see a solution for problem 1.

    Read the article

  • Using R in Processing through rJava/JRI?

    - by tommy-o-dell
    Hi guys, Is it possible to run R in Processing through rJava/JRI? If I deployed a Processing app on the web, would the client need R on their system? I'm looking to create an interactive information dashboard that I can deploy on the web. It seems that Processing is probably my best bet for the interactive/web part of things. Unfortunately, it doesn't look like there are many math/stats functions built-in. And there aren't any libraries for plotting data either. I've been using R and gpplot2 for a few months and am thrilled (amazed) at how easily it manipulates and plots data. So I'm wondering now if can get the best of both worlds and run R through a Processing applet. From the JRI website: JRI is a Java/R Interface, which allows to run R inside Java applications as a single thread. Basically it loads R dynamic library into Java and provides a Java API to R functionality. It supports both simple calls to R functions and a full running REPL. In a sense JRI is the inverse of rJava and both can be combined (i.e. you can run R code inside JRI that calls back to the JVM via rJava). The JGR project makes the full use of both JRI and rJava to provide a full Java GUI for R. JRI uses native code, but it supports all platforms where Sun's Java (or compatible) is available, including Windows, Mac OS X, Sun and Linux (both 32-bit and 64-bit). Thanks for the advice :)

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >