Search Results

Search found 5945 results on 238 pages for 'green threads'.

Page 19/238 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • help me reason about F# threads

    - by Kevin Cantu
    In goofing around with some F# (via MonoDevelop), I have written a routine which lists files in a directory with one thread: let rec loop (path:string) = Array.append ( path |> Directory.GetFiles ) ( path |> Directory.GetDirectories |> Array.map loop |> Array.concat ) And then an asynchronous version of it: let rec loopPar (path:string) = Array.append ( path |> Directory.GetFiles ) ( let paths = path |> Directory.GetDirectories if paths <> [||] then [| for p in paths -> async { return (loopPar p) } |] |> Async.Parallel |> Async.RunSynchronously |> Array.concat else [||] ) On small directories, the asynchronous version works fine. On bigger directories (e.g. many thousands of directories and files), the asynchronous version seems to hang. What am I missing? I know that creating thousands of threads is never going to be the most efficient solution -- I only have 8 CPUs -- but I am baffled that for larger directories the asynchronous function just doesn't respond (even after a half hour). It doesn't visibly fail, though, which baffles me. Is there a thread pool which is exhausted? How do these threads actually work?

    Read the article

  • How can I synchronize database access between a write-thread and a read-thread?

    - by Runcible
    My program has two threads: Main execution thread that handles user input and queues up database writes A utility thread that wakes up every second and flushes the writes to the database Inside the main thread, I occasionally need to make reads on the database. When this happens, performance is not important, but correctness is. (In a perfect world, I would be reading from a cache, not making a round-trip to the database - but let's put that aside for the sake of discussion.) How do I make sure that the main thread sees a correct / quiescent database? A standard mutex won't work, since I run the risk of having the main thread grab the mutex before the data gets flushed to the database. This would be a big race condition. What I really want is some sort of mutex that lets the main thread of execution proceed only AFTER the mutex has been grabbed and released once. Does such a thing exist? What's the best way to solve this problem?

    Read the article

  • what is value of x for load and store

    - by Kevinniceguy
    This is some challenge On a single processor system, in which load and store are assumed to be atomic, what are all the possible values for x after both threads have completed in the following execution, assuming that x is initialised to O? Hint: you need to consider how this code might be compiled into machine language. for (int i = 0; i < 5; i++) : x = x + 1; for (int j = 0; j < 5; j++) : x = x + 1;

    Read the article

  • How to wait for thread to finish with .NET?

    - by Maxim Z.
    I've never really used threading before in C# where I need to have two threads, as well as the main UI thread. Basically, I have the following. public void StartTheActions() { //Starting thread 1.... Thread t1 = new Thread(new ThreadStart(action1)); t1.Start(); //Now, I want for the main thread (which is calling StartTheActions() ) to wait for t1 to finish (I have created an event in action1() for this) and then start t2... //HOW DO I DO THIS? Thread t2 = new Thread(new ThreadStart(action2)); t2.Start(); } So, essentially, my question is how to have a thread wait for another one to finish. What is the best way to do this? Thanks!

    Read the article

  • Why a thread is aborted in ASP.NET MVC (again)?

    - by Dario Solera
    Here is what I do in a controller action: create and start a new Thread that does a relatively long processing task (~30 seconds on average, but might be several minutes) immediately return the page response so the user knows processing has started (trivially, a Json with a task ID for polling purposes). At some random point, ThreadAbortException is thrown, so the async task does not complete. The exception is not thrown every time, it just happens randomly roughly 25% of the times. Points to note: I'm not calling Response.End or Response.Redirect - there isn't even a request running when the exception is thrown I tried using ThreadPool and I got the same behavior I know running threads in ASP.NET has several caveats but I don't care right now Any suggestion?

    Read the article

  • Threaded Django task doesn't automatically handle transactions or db connections?

    - by Gabriel Hurley
    I've got Django set up to run some recurring tasks in their own threads, and I noticed that they were always leaving behind unfinished database connection processes (pgsql "Idle In Transaction"). I looked through the Postgres logs and found that the transactions weren't being completed (no ROLLBACK). I tried using the various transaction decorators on my functions, no luck. I switched to manual transaction management and did the rollback manually, that worked, but still left the processes as "Idle". So then I called connection.close(), and all is well. But I'm left wondering, why doesn't Django's typical transaction and connection management work for these threaded tasks that are being spawned from the main Django thread?

    Read the article

  • How to fire off a asych thread in a web application, and gaurantee only 1 thread fires?

    - by Blankman
    I want to cache a object in memory. Regenerating the object when the cache expires is fairly expensive, so I want to do the following: When the cache is "about" to expire, I want to fire off a asychronous thread that will go and rebuild the object and then reset the cache. One thing I am worry about is multiple threads firing to fetch the object to cache, I only want a single thread doing this, realizing many people will be hitting the website. This might not be the best use case to do this, but I want to know how to do this sort of thing.

    Read the article

  • Async stream writing in a thread

    - by blez
    I have a thread in which I write to 2 streams. The problem is that the thread is blocked until the first one finishes writing (until all data is transferred on the other side of the pipe), and I don't want that. Is there a way to make it asynchronous? chunkOutput is a Dictionary filled with data from multiple threads, so the faster checking for existing keys is, the faster the pipe will write. void ConsumerMethod(object totalChunks) { while(true) { if (chunkOutput.ContainsKey(curChunk)) { if (outputStream != null && chunkOutput[curChunk].Length > 0) { outputStream.Write(chunkOutput[curChunk]); // <-- here it stops } ChunkDownloader.AppendData("outfile.dat", chunkOutput[curChunk], chunkOutput[curChunk].Length); curChunk++; if (curChunk >= (int) totalChunks) return; } Thread.Sleep(10); } }

    Read the article

  • Python: Huge file reading by using linecache Vs normal file access open()

    - by user335223
    Hi, I am in a situation where multiple threads reading the same huge file with mutliple file pointers to same file. The file will have atleast 1 million lines. Eachline's length varies from 500 characters to 1500 characters. There won't "write" operations on the file. Each thread will start reading the same file from different lines. Which is the efficient way..? Using the Python's linecache or normal readline() or is there anyother effient way?

    Read the article

  • How can I prevent ADO from creating multiple SPIDs?

    - by stusmith
    I'm working on an application that creates a single ADO connection and keeps it open for the lifetime of the application. I have connection pooling turned off. (Please ignore the fact that this might not be best practice for the purposes of this question). If I spawn a new thread and use the exact same ADO connection, it uses a new SPID behind the scenes. Is there anyway to ensure an ADO connection always uses the same SPID, across all threads? (For reference the application is VC++ using ADO via COM to SQL Server).

    Read the article

  • ContextSwitchDeadlock Was Detected error in C#

    - by assassin
    Hi, I am running a C# application, and during run-time I get the following error: The CLR has been unable to transition from COM context 0x20e480 to COM context 0x20e5f0 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations. Can anyone please help me out with the problem here? Thanks a lot.

    Read the article

  • Clarification on Threads and Run Loops In Cocoa

    - by dubbeat
    I'm trying to learn about threading and I'm thoroughly confused. I'm sure all the answers are there in the apple docs but I just found it really hard to breakdown and digest. Maybe somebody could clear a thing or 2 up for me. 1)performSelectorOnMainThread Does the above simply register an event in the main run loop or is it somehow a new thread even though the method says "mainThread"? If the purpose of threads is to relieve processing on the main thread how does this help? 2) RunLoops Is it true that if I want to create a completely seperate thread I use "detachNewThreadSelector"? Does calling start on this initiate a default run loop for the thread that has been created? If so where do run loops come into it? 3) And Finally , I've seen examples using NSOperationQueue. Is it true to say that If you use performSelectorOnMainThread the threads are in a queue anyway so NSOperation is not needed? 4) Should I forget about all of this and just use the Grand Central Dispatch instead?

    Read the article

  • Processing a database queue across multiple threads - design advice

    - by rwmnau
    I have a SQL Server table full of orders that my program needs to "follow up" on (call a webservice to see if something has been done with them). My application is multi-threaded, and could have instances running on multiple servers. Currently, every so often (on a Threading timer), the process selects 100 rows, at random (ORDER BY NEWID()), from the list of "unconfirmed" orders and checks them, marking off any that come back successfully. The problem is that there's a lot of overlap between the threads, and between the different processes, and their's no guarantee that a new order will get checked any time soon. Also, some orders will never be "confirmed" and are dead, which means that they get in the way of orders that need to be confirmed, slowing the process down if I keep selecting them over and over. What I'd prefer is that all outstanding orders get checked, systematically. I can think of two easy ways do this: The application fetches one order to check at a time, passing in the last order it checked as a parameter, and SQL Server hands back the next order that's unconfirmed. More database calls, but this ensures that every order is checked in a reasonable timeframe. However, different servers may re-check the same order in succession, needlessly. The SQL Server keeps track of the last order it asked a process to check up on, maybe in a table, and gives a unique order to every request, incrementing its counter. This involves storing the last order somewhere in SQL, which I wanted to avoid, but it also ensures that threads won't needlessly check the same orders at the same time Are there any other ideas I'm missing? Does this even make sense? Let me know if I need some clarification.

    Read the article

  • using threads in menu options

    - by vbNewbie
    I have an app that has a console menu with 2/3 selections. One process involves uploading a file and performing a lengthy search process on its contents, whilst another process involves SQL queries and is an interactive process with the user. I wish to use threads to allow one process to run and the menu to offer the option for the second process to run. However you cannot run the first process twice. I have created threads and corrected some compilation errors but the threading options are not working correctly. Any help appreciated. main... Dim tm As Thread = New Thread(AddressOf loadFile) Dim ts As Thread = New Thread(AddressOf reports) .... While Not response.Equals("3") Try Console.Write("Enter choice: ") response = Console.ReadLine() Console.WriteLine() If response.Equals("1") Then Console.WriteLine("Thread 1 doing work") tm.SetApartmentState(ApartmentState.STA) tm.IsBackground = True tm.Start() response = String.Empty ElseIf response.Equals("2") Then Console.WriteLine("Starting a second Thread") ts.Start() response = String.Empty End If ts.Join() tm.Join() Catch ex As Exception errormessage = ex.Message End Try End While I realize that a form based will be easier to implement with perhaps just calling different forms to handle the processes.But I really dont have that option now since the console app will be added to api later. But here are my two processes from the menu functions. Also not sure what to do with the boolean variabel again as suggested below. Private Sub LoadFile() Dim dialog As New OpenFileDialog Dim response1 As String = Nothing Dim filepath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) dialog.InitialDirectory = filepath If dialog.ShowDialog() = DialogResult.OK Then fileName = dialog.FileName ElseIf DialogResult.Cancel Then Exit Sub End If Console.ResetColor() Console.Write("Begin Search -- Discovery Search, y or n? ") response1 = Console.ReadLine() If response1 = "y" Then Search() ElseIf response1 = "n" Then Console.Clear() main() End If isRunning = False End Sub and the second one Private Shared Sub report() Dim rptGen As New SearchBlogDiscovery.rptGeneration Console.WriteLine("Tread Process started") rptGen.main() Console.WriteLine("Thread Process ended") isRunning = False End Sub

    Read the article

  • Getting data from JFrame AFTER the form is filled

    - by mary jane
    I'm trying to get data for my application from a form set in an external window (getDataWindow extends javax.swing.JFrame). The problem is that functions are executed before form is filled in. getDataWindow dataW=new getDataWindow(); dataW.setVisible(true); size=dataW.returnSize(); I've tried also adding additional boolean variable to getDataWindow getDataWindow dataW=new getDataWindow(); dataW.setVisible(true); while(!dataW.checkIfReady()){wait();} size=dataW.returnSize(); But it makes also the window wait (it appears but it's black inside and nothing happens). I think i should create some threads for that - I've tried to call a window making function getDataWindow in java.awt.EventQueue.invokeLater(new Runnable()) but I had to initialize dataW earlier so dataW.checkIfReady() could be called, so it is a catch 22.

    Read the article

  • Do I need to using locking against integers in c++ threads

    - by Shane MacLaughlin
    The title says it all really. If I am accessing a single integer type (e.g. long, int, bool, etc...) in multiple threads, do I need to use a synchronisation mechanism such as a mutex to lock them. My understanding is that as atomic types, I don't need to lock access to a single thread, but I see a lot of code out there that does use locking. Profiling such code shows that there is a significant performance hit for using locks, so I'd rather not. So if the item I'm accessing corresponds to a bus width integer (e.g. 4 bytes on a 32 bit processor) do I need to lock access to it when it is being used across multiple threads? Put another way, if thread A is writing to integer variable X at the same time as thread B is reading from the same variable, is it possible that thread B could end up a few bytes of the previous value mixed in with a few bytes of the value being written? Is this architecture dependent, e.g. ok for 4 byte integers on 32 bit systems but unsafe on 8 byte integers on 64 bit systems? Edit: Just saw this related post which helps a fair bit.

    Read the article

  • New thread per client connection in socket server?

    - by Olaseni
    I am trying to optimize multiple connections per time to a TCP socket server. Is it considered good practice, or even rational to initiate a new thread in the listening server every time I receive a connection request? At what time should I begin to worry about a server based on this infrastructure? What is the maximum no of background threads I can work, until it doesn't make any sense anymore? Platform is C#, framework is Mono, target OS is CentOS, RAM is 2.4G, server is on the clouds, and I'm expecting about 200 connection requests per second.

    Read the article

  • Reading a variable messes it up?!?!

    - by EpsilonVector
    We have the following line of code: printf("%d\n", toc->runlist.next); printf("%d\n", toc->runlist.next); These are the definitions: typedef struct thread_overview_control{ int id[NR_UTHREADS]; list_t runlist; int active_counter; int main_thread; int need_resched; } thread_overview_control; thread_overview_control* toc; What I'm trying to do is implement user threads. For some reason the output of the above code at the point where our test run crushes is: 12345678 //some address 0 //NOW IT'S NULL?!?!?! How can this happen?? All we do is read a variable. And the strange thing is, without printf's there are no crashes. What's going on?

    Read the article

  • wxpython - Running threads sequentially without blocking GUI

    - by ryantmer
    I've got a GUI script with all my wxPython code in it, and a separate testSequences module that has a bunch of tasks that I run based on input from the GUI. The tasks take a long time to complete (from 20 seconds to 3 minutes), so I want to thread them, otherwise the GUI locks up while they're running. I also need them to run one after another, since they all use the same hardware. (My rationale behind threading is simply to prevent the GUI from locking up.) I'd like to have a "Running" message (with varying number of periods after it, i.e. "Running", "Running.", "Running..", etc.) so the user knows that progress is occurring, even though it isn't visible. I'd like this script to run the test sequences in separate threads, but sequentially, so that the second thread won't be created and run until the first is complete. Since this is kind of the opposite of the purpose of threads, I can't really find any information on how to do this... Any help would be greatly appreciated. Thanks in advance! gui.py import testSequences from threading import Thread #wxPython code for setting everything up here... for j in range(5): testThread = Thread(target=testSequences.test1) testThread.start() while testThread.isAlive(): #wait until the previous thread is complete time.sleep(0.5) i = (i+1) % 4 self.status.SetStatusText("Running"+'.'*i) testSequences.py import time def test1(): for i in range(10): print i time.sleep(1) (Obviously this isn't the actual test code, but the idea is the same.)

    Read the article

  • Thread toggling

    - by sid
    Hi all, In Ubuntu, I am running 2 'C' applications, When I press key up/down the applications are alternatively getting the events. What might be the problem/solution? Ex: I have 'A application' and 'B application', I launch 'A application' and press the key up/down its working fine. If I simultaneously launch 'B application' and focus is on 'B application' then pressing key up/down will toggle between 'A application' & 'B application' so 2 times I have to press the key to move on 'B application'(focus is on 'B application'). 'A application' and 'B application' are threads. Thanks in advance-opensid

    Read the article

  • Does SetThreadPriority cause thread reschedulling?

    - by Suma
    Consider following situation, assuming single CPU system: thread A is running with a priority THREAD_PRIORITY_NORMAL, signals event E thread B with a priority THREAD_PRIORITY_LOWEST is waiting for an event E (Note: at this point the thread is not scheduled because it is runnable, but A is higher priority and runnable as well) thread A calls SetThreadPriority(B, THREAD_PRIORITY_ABOVE_NORMAL) Is thread B re-scheduled immediately to run, or is thread A allowed to continue until current time-slice is over, and B is scheduled only once a new time-slice has begun? I would be interested to know the answer for WinXP, Vista and Win7, if possible. Note: the scenario above is simplified from my real world code, where multiple threads are running on multiple cores, but the main object of the question stays: does SetThreadPriority cause thread scheduling to happen?

    Read the article

  • Pass off execution to different/specific thread in Java

    - by Mike
    I have about 4 threads. One thread keeps checking some data that the other thread is updating. The others are doing some processing in the background. All have been started at this point. My question is when the checking thread sees that the data has not been updated yet I currently sleep for a little bit but is there any way for me to tell the system to back to executing the thread that does the updating? That or is there any way I can put something like a listener on the data(a String) and once its updated an event will fire that will do what it needs to do? I tried using yield() and it seemed to just keep returning to the thread I called yield() from. Thanks

    Read the article

  • Can a thread call wait() on two locks at once in Java (6)

    - by Dr. Monkey
    I've just been messing around with threads in Java to get my head around them (it seems like the best way to do so) and now understand what's going on with synchronize, wait() and notify(). I'm curious about whether there's a way to wait() on two resources at once. I think the following won't quite do what I'm thinking of: synchronized(token1) { synchronized(token2) { token1.wait(); token2.wait(); //won't run until token1 is returned System.out.println("I got both tokens back"); } } In this (very contrived) case token2 will be held until token1 is returned, then token1 will be held until token2 is returned. The goal is to release both token1 and token2, then resume when both are available (note that moving the token1.wait() outside the inner synchronized loop is not what I'm getting at). A loop checking whether both are available might be more appropriate to achieve this behaviour (would this be getting near the idea of double-check locking?), but would use up extra resources - I'm not after a definitive solution since this is just to satisfy my curiosity.

    Read the article

  • Threads to make video out of images

    - by masood
    updates: I think/ suspect the imageIO is not thread safe. shared by all threads. the read() call might use resources that are also shared. Thus it will give the performance of a single thread no matter how many threads used. ? if its correct . what is the solution (in practical code) Single request and response model at one time do not utilizes full network/internet bandwidth, thus resulting in low performance. (benchmark is of half speed utilization or even lower) This is to make a video out of an IP cam that gives a new image on each request. http://149.5.43.10:8001/snapshot.jpg It makes a delay of 3 - 8 seconds no matter what I do. Changed thread no. and thread time intervals, debugged the code by System.out.println statements to see if threads work. All seems normal. Any help? Please show some practical code. You may modify mine. This code works (javascript) with much smoother frame rate and max bandwidth usage. but the later code (java) dont. same 3 to 8 seconds gap. <!DOCTYPE html> <html> <head> <script type="text/javascript"> (function(){ var img="/*url*/"; var interval=50; var pointer=0; function showImg(image,idx) { if(idx<=pointer) return; document.body.replaceChild(image,document.getElementsByTagName("img")[0]); pointer=idx; preload(); } function preload() { var cache=null,idx=0;; for(var i=0;i<5;i++) { idx=Date.now()+interval*(i+1); cache=new Image(); cache.onload=(function(ele,idx){return function(){showImg(ele,idx);};})(cache,idx); cache.src=img+"?"+idx; } } window.onload=function(){ document.getElementsByTagName("img")[0].onload=preload; document.getElementsByTagName("img")[0].src="/*initial url*/"; }; })(); </script> </head> <body> <img /> </body> </html> and of java (with problem) : package camba; import java.applet.Applet; import java.awt.Button; import java.awt.Graphics; import java.awt.Image; import java.awt.Label; import java.awt.Panel; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import java.security.Timestamp; import java.util.Date; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.imageio.ImageIO; public class Camba extends Applet implements ActionListener{ Image img; TextField textField; Label label; Button start,stop; boolean terminate = false; long viewTime; public void init(){ label = new Label("please enter camera URL "); add(label); textField = new TextField(30); add(textField); start = new Button("Start"); add(start); start.addActionListener(this); stop = new Button("Stop"); add(stop); stop.addActionListener(this); } public void actionPerformed(ActionEvent e){ Button source = (Button)e.getSource(); if(source.getLabel() == "Start"){ for (int i = 0; i < 7; i++) { myThread(50*i); } System.out.println("start..."); } if(source.getLabel() == "Stop"){ terminate = true; System.out.println("stop..."); } } public void paint(Graphics g) { update(g); } public void update(Graphics g){ try{ viewTime = System.currentTimeMillis(); g.drawImage(img, 100, 100, this); } catch(Exception e) { e.printStackTrace(); } } public void myThread(final int sleepTime){ new Thread(new Runnable() { public void run() { while(!terminate){ try { TimeUnit.MILLISECONDS.sleep(sleepTime); } catch (InterruptedException ex) { ex.printStackTrace(); } long requestTime= 0; Image tempImage = null; try { URL pic = null; requestTime= System.currentTimeMillis(); pic = new URL(getDocumentBase(), textField.getText()); tempImage = ImageIO.read(pic); } catch(Exception e) { e.printStackTrace(); } if(requestTime >= /*last view time*/viewTime){ img = tempImage; Camba.this.repaint(); } } }}).start(); System.out.println("thread started..."); } }

    Read the article

  • Why is UITableView not reloading (even on the main thread)?

    - by radesix
    I have two programs that basically do the same thing. They read an XML feed and parse the elements. The design of both programs is to use an asynchronous NSURLConnection to get the data then to spawn a new thread to handle the parsing. As batches of 5 items are parsed it calls back to the main thread to reload the UITableView. My issue is it works fine in one program, but not the other. I know that the parsing is actually occuring on the background thread and I know that [tableView reloadData] is executing on the main thread; however, it doesn't reload the table until all parsing is complete. I'm stumped. As far as I can tell... both programs are structured exactly the same way. Here is some code from the app that isn't working correctly. - (void)startConnectionWithURL:(NSString *)feedURL feedList:(NSMutableArray *)list { self.feedList = list; // Use NSURLConnection to asynchronously download the data. This means the main thread will not be blocked - the // application will remain responsive to the user. // // IMPORTANT! The main thread of the application should never be blocked! Also, avoid synchronous network access on any thread. // NSURLRequest *feedURLRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:feedURL]]; self.bloggerFeedConnection = [[[NSURLConnection alloc] initWithRequest:feedURLRequest delegate:self] autorelease]; // Test the validity of the connection object. The most likely reason for the connection object to be nil is a malformed // URL, which is a programmatic error easily detected during development. If the URL is more dynamic, then you should // implement a more flexible validation technique, and be able to both recover from errors and communicate problems // to the user in an unobtrusive manner. NSAssert(self.bloggerFeedConnection != nil, @"Failure to create URL connection."); // Start the status bar network activity indicator. We'll turn it off when the connection finishes or experiences an error. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { self.bloggerData = [NSMutableData data]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [bloggerData appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { self.bloggerFeedConnection = nil; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; // Spawn a thread to fetch the link data so that the UI is not blocked while the application parses the XML data. // // IMPORTANT! - Don't access UIKit objects on secondary threads. // [NSThread detachNewThreadSelector:@selector(parseFeedData:) toTarget:self withObject:bloggerData]; // farkData will be retained by the thread until parseFarkData: has finished executing, so we no longer need // a reference to it in the main thread. self.bloggerData = nil; } If you read this from the top down you can see when the NSURLConnection is finished I detach a new thread and call parseFeedData. - (void)parseFeedData:(NSData *)data { // You must create a autorelease pool for all secondary threads. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; self.currentParseBatch = [NSMutableArray array]; self.currentParsedCharacterData = [NSMutableString string]; self.feedList = [NSMutableArray array]; // // It's also possible to have NSXMLParser download the data, by passing it a URL, but this is not desirable // because it gives less control over the network, particularly in responding to connection errors. // NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; [parser setDelegate:self]; [parser parse]; // depending on the total number of links parsed, the last batch might not have been a "full" batch, and thus // not been part of the regular batch transfer. So, we check the count of the array and, if necessary, send it to the main thread. if ([self.currentParseBatch count] > 0) { [self performSelectorOnMainThread:@selector(addLinksToList:) withObject:self.currentParseBatch waitUntilDone:NO]; } self.currentParseBatch = nil; self.currentParsedCharacterData = nil; [parser release]; [pool release]; } In the did end element delegate I check to see that 5 items have been parsed before calling the main thread to perform the update. - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:kItemElementName]) { [self.currentParseBatch addObject:self.currentItem]; parsedItemsCounter++; if (parsedItemsCounter % kSizeOfItemBatch == 0) { [self performSelectorOnMainThread:@selector(addLinksToList:) withObject:self.currentParseBatch waitUntilDone:NO]; self.currentParseBatch = [NSMutableArray array]; } } // Stop accumulating parsed character data. We won't start again until specific elements begin. accumulatingParsedCharacterData = NO; } - (void)addLinksToList:(NSMutableArray *)links { [self.feedList addObjectsFromArray:links]; // The table needs to be reloaded to reflect the new content of the list. if (self.viewDelegate != nil && [self.viewDelegate respondsToSelector:@selector(parser:didParseBatch:)]) { [self.viewDelegate parser:self didParseBatch:links]; } } Finally, the UIViewController delegate: - (void)parser:(XMLFeedParser *)parser didParseBatch:(NSMutableArray *)parsedBatch { NSLog(@"parser:didParseBatch:"); [self.selectedBlogger.feedList addObjectsFromArray:parsedBatch]; [self.tableView reloadData]; } If I write to the log when my view controller delegate fires to reload the table and when cellForRowAtIndexPath fires as it's rebuilding the table then the log looks something like this: parser:didParseBatch: parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: parser:didParseBatch: parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: parser:didParseBatch: parser:didParseBatch: parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath Clearly, the tableView is not reloading when I tell it to every time. The log from the app that works correctly looks like this: parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >