Search Results

Search found 8588 results on 344 pages for 'thread abort'.

Page 122/344 | < Previous Page | 118 119 120 121 122 123 124 125 126 127 128 129  | Next Page >

  • Lockless queue implementation ends up having a loop under stress

    - by Fozi
    I have lockless queues written in C in form of a linked list that contains requests from several threads posted to and handled in a single thread. After a few hours of stress I end up having the last request's next pointer pointing to itself, which creates an endless loop and locks up the handling thread. The application runs (and fails) on both Linux and Windows. I'm debugging on Windows, where my COMPARE_EXCHANGE_PTR maps to InterlockedCompareExchangePointer. This is the code that pushes a request to the head of the list, and is called from several threads: void push_request(struct request * volatile * root, struct request * request) { assert(request); do { request->next = *root; } while(COMPARE_EXCHANGE_PTR(root, request, request->next) != request->next); } This is the code that gets a request from the end of the list, and is only called by a single thread that is handling them: struct request * pop_request(struct request * volatile * root) { struct request * volatile * p; struct request * request; do { p = root; while(*p && (*p)->next) p = &(*p)->next; // <- loops here request = *p; } while(COMPARE_EXCHANGE_PTR(p, NULL, request) != request); assert(request->next == NULL); return request; } Note that I'm not using a tail pointer because I wanted to avoid the complication of having to deal with the tail pointer in push_request. However I suspect that the problem might be in the way I find the end of the list. There are several places that push a request into the queue, but they all look generaly like this: // device->requests is defined as struct request * volatile requests; struct request * request = malloc(sizeof(struct request)); if(request) { // fill out request fields push_request(&device->requests, request); sem_post(device->request_sem); } The code that handles the request is doing more than that, but in essence does this in a loop: if(sem_wait_timeout(device->request_sem, timeout) == sem_success) { struct request * request = pop_request(&device->requests); // handle request free(request); } I also just added a function that is checking the list for duplicates before and after each operation, but I'm afraid that this check will change the timing so that I will never encounter the point where it fails. (I'm waiting for it to break as I'm writing this.) When I break the hanging program the handler thread loops in pop_request at the marked position. I have a valid list of one or more requests and the last one's next pointer points to itself. The request queues are usually short, I've never seen more then 10, and only 1 and 3 the two times I could take a look at this failure in the debugger. I thought this through as much as I could and I came to the conclusion that I should never be able to end up with a loop in my list unless I push the same request twice. I'm quite sure that this never happens. I'm also fairly sure (although not completely) that it's not the ABA problem. I know that I might pop more than one request at the same time, but I believe this is irrelevant here, and I've never seen it happening. (I'll fix this as well) I thought long and hard about how I can break my function, but I don't see a way to end up with a loop. So the question is: Can someone see a way how this can break? Can someone prove that this can not? Eventually I will solve this (maybe by using a tail pointer or some other solution - locking would be a problem because the threads that post should not be locked, I do have a RW lock at hand though) but I would like to make sure that changing the list actually solves my problem (as opposed to makes it just less likely because of different timing).

    Read the article

  • Concurrency and Calendar classes

    - by fbielejec
    I have a thread (class implementing runnable, called AnalyzeTree) organised around a hash map (ConcurrentMap slicesMap). The class goes through the data (called trees here) in the large text file and parses the geographical coordinates from it to the HashMap. The idea is to process one tree at a time and add or grow the values according to the key (which is just a Double value representing time). The relevant part of code looks like this: // grow map entry if key exists if (slicesMap.containsKey(sliceTime)) { double[] imputedLocation = imputeValue( location, parentLocation, sliceHeight, nodeHeight, parentHeight, rate, useTrueNoise, currentTreeNormalization, precisionArray); slicesMap.get(sliceTime).add( new Coordinates(imputedLocation[1], imputedLocation[0], 0.0)); // start new entry if no such key in the map } else { List<Coordinates> coords = new ArrayList<Coordinates>(); double[] imputedLocation = imputeValue( location, parentLocation, sliceHeight, nodeHeight, parentHeight, rate, useTrueNoise, currentTreeNormalization, precisionArray); coords.add(new Coordinates(imputedLocation[1], imputedLocation[0], 0.0)); slicesMap.putIfAbsent(sliceTime, coords); // slicesMap.put(sliceTime, coords); }// END: key check And the class is called like this (executor is ExecutorService executor = Executors.newFixedThreadPool(NTHREDS) ): mrsd = new SpreadDate(mrsdString); int readTrees = 1; while (treesImporter.hasTree()) { currentTree = (RootedTree) treesImporter.importNextTree(); executor.submit(new AnalyzeTree(currentTree, precisionString, coordinatesName, rateString, numberOfIntervals, treeRootHeight, timescaler, mrsd, slicesMap, useTrueNoise)); // new AnalyzeTree(currentTree, precisionString, // coordinatesName, rateString, numberOfIntervals, // treeRootHeight, timescaler, mrsd, slicesMap, // useTrueNoise).run(); readTrees++; }// END: while has trees Now this is running into troubles when executed in parallel (the commented part running sequentially is fine), I thought it might throw a ConcurrentModificationException, but apparently the problem is in mrsd (instance of SpreadDate object, which is simply a class for date related calculations). The SpreadDate class looks like this: public class SpreadDate { private Calendar cal; private SimpleDateFormat formatter; private Date stringdate; public SpreadDate(String date) throws ParseException { // if no era specified assume current era String line[] = date.split(" "); if (line.length == 1) { StringBuilder properDateStringBuilder = new StringBuilder(); date = properDateStringBuilder.append(date).append(" AD") .toString(); } formatter = new SimpleDateFormat("yyyy-MM-dd G", Locale.US); stringdate = formatter.parse(date); cal = Calendar.getInstance(); } public long plus(int days) { cal.setTime(stringdate); cal.add(Calendar.DATE, days); return cal.getTimeInMillis(); }// END: plus public long minus(int days) { cal.setTime(stringdate); cal.add(Calendar.DATE, -days); //line 39 return cal.getTimeInMillis(); }// END: minus public long getTime() { cal.setTime(stringdate); return cal.getTimeInMillis(); }// END: getDate } And the stack trace from when exception is thrown: java.lang.ArrayIndexOutOfBoundsException: 58 at sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate(BaseCalendar.java:454) at java.util.GregorianCalendar.computeFields(GregorianCalendar.java:2098) at java.util.GregorianCalendar.computeFields(GregorianCalendar.java:2013) at java.util.Calendar.setTimeInMillis(Calendar.java:1126) at java.util.GregorianCalendar.add(GregorianCalendar.java:1020) at utils.SpreadDate.minus(SpreadDate.java:39) at templates.AnalyzeTree.run(AnalyzeTree.java:88) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:636) If a move the part initializing mrsd to the AnalyzeTree class it runs without any problems - however it is not very memory efficient to initialize class each time this thread is running, hence my concerns. How can it be remedied?

    Read the article

  • How do you send a named pipe string from umnanaged to managed code space?

    - by billmcf
    I appear to have a named pipes 101 issue. I have a very simple set up to connect a simplex named pipe transmitting from a C++ unmanaged app to a C# managed app. The pipe connects, but I cannot send a "message" through the pipe unless I close the handle which appears to flush the buffer and pass the message through. It's like the message is blocked. I have tried reversing the roles of client/server and invoking them with different Flag combinations without any luck. I can easily send messages in the other direction from C# managed to C++ unmanaged. Does anyone have any insight. Can any of you guys successfully send messages from C++ unmanaged to C# managed? I can find plenty of examples of intra amanged or unmanaged pipes but not inter managed to/from unamanged - just claims to be able to do it. In the listings, I have omitted much of the wrapper stuff for clarity. The key bits I believe that are relevant are the pipe connection/creation/read and write methods. Don't worry too much about blocking/threading here. C# Server side // This runs in its own thread and so it is OK to block private void ConnectToClient() { // This server will listen to the sending client if (m_InPipeStream == null) { m_InPipeStream = new NamedPipeServerStream("TestPipe", PipeDirection.In, 1); } // Wait for client to connect to our server m_InPipeStream.WaitForConnection(); // Verify client is running if (!m_InPipeStream.IsConnected) { return; } // Start listening for messages on the client stream if (m_InPipeStream != null && m_InPipeStream.CanRead) { ReadThread = new Thread(new ParameterizedThreadStart(Read)); ReadThread.Start(m_InPipeStream); } } // This runs in its own thread and so it is OK to block private void Read(object serverObj) { NamedPipeServerStream pipeStream = (NamedPipeServerStream)serverObj; using (StreamReader sr = new StreamReader(pipeStream)) { while (true) { string buffer = "" ; try { // Blocks here until the handle is closed by the client-side!! buffer = sr.ReadLine(); // <<<<<<<<<<<<<< Sticks here } catch { // Read error break; } // Client has disconnected? if (buffer == null || buffer.Length == 0) break; // Fire message received event if message is non-empty if (MessageReceived != null && buffer != "") { MessageReceived(buffer); } } } } C++ client side // Static - running in its own thread. DWORD CNamedPipe::ListenForServer(LPVOID arg) { // The calling app (this) is passed as the parameter CNamedPipe* app = (CNamedPipe*)arg; // Out-Pipe: connect as a client to a waiting server app->m_hOutPipeHandle = CreateFile("\\\\.\\pipe\\TestPipe", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // Could not create handle if (app->m_hInPipeHandle == NULL || app->m_hInPipeHandle == INVALID_HANDLE_VALUE) { return 1; } return 0; } // Sends a message to the server BOOL CNamedPipe::SendMessage(CString message) { DWORD dwSent; if (m_hOutPipeHandle == NULL || m_hOutPipeHandle == INVALID_HANDLE_VALUE) { return FALSE; } else { BOOL bOK = WriteFile(m_hOutPipeHandle, message, message.GetLength()+1, &dwSent, NULL); //FlushFileBuffers(m_hOutPipeHandle); // <<<<<<< Tried this return (!bOK || (message.GetLength()+1) != dwSent) ? FALSE : TRUE; } } // Somewhere in the Windows C++/MFC code... ... // This write is non-blocking. It just passes through having loaded the pipe. m_pNamedPipe->SendMessage("Hi de hi"); ...

    Read the article

  • Log4j: Events appear in the wrong logfile

    - by Markus
    Hi there! To be able to log and trace some events I've added a LoggingHandler class to my java project. Inside this class I'm using two different log4j logger instances - one for logging an event and one for tracing an event into different files. The initialization block of the class looks like this: public void initialize() { System.out.print("starting logging server ..."); // create logger instances logLogger = Logger.getLogger("log"); traceLogger = Logger.getLogger("trace"); // create pattern layout String conversionPattern = "%c{2} %d{ABSOLUTE} %r %p %m%n"; try { patternLayout = new PatternLayout(); patternLayout.setConversionPattern(conversionPattern); } catch (Exception e) { System.out.println("error: could not create logger layout pattern"); System.out.println(e); System.exit(1); } // add pattern to file appender try { logFileAppender = new FileAppender(patternLayout, logFilename, false); traceFileAppender = new FileAppender(patternLayout, traceFilename, false); } catch (IOException e) { System.out.println("error: could not add logger layout pattern to corresponding appender"); System.out.println(e); System.exit(1); } // add appenders to loggers logLogger.addAppender(logFileAppender); traceLogger.addAppender(traceFileAppender); // set logger level logLogger.setLevel(Level.INFO); traceLogger.setLevel(Level.INFO); // start logging server loggingServer = new LoggingServer(logLogger, traceLogger, serverPort, this); loggingServer.start(); System.out.println(" done"); } To make sure that only only thread is using the functionality of a logger instance at the same time each logging / tracing method calls the logging method .info() inside a synchronized-block. One example looks like this: public void logMessage(String message) { synchronized (logLogger) { if (logLogger.isInfoEnabled() && logFileAppender != null) { logLogger.info(instanceName + ": " + message); } } } If I look at the log files, I see that sometimes a event appears in the wrong file. One example: trace 10:41:30,773 11080 INFO masterControl(192.168.2.21): string broadcast message was pushed from 1267093 to vehicle 1055293 (slaveControl 1) trace 10:41:30,784 11091 INFO masterControl(192.168.2.21): string broadcast message was pushed from 1156513 to vehicle 1105792 (slaveControl 1) trace 10:41:30,796 11103 INFO masterControl(192.168.2.21): string broadcast message was pushed from 1104306 to vehicle 1055293 (slaveControl 1) trace 10:41:30,808 11115 INFO masterControl(192.168.2.21): vehicle 1327879 was pushed to slave control 1 10:41:30,808 11115 INFO masterControl(192.168.2.21): string broadcast message was pushed from 1101572 to vehicle 106741 (slaveControl 1) trace 10:41:30,820 11127 INFO masterControl(192.168.2.21): string broadcast message was pushed from 1055293 to vehicle 1104306 (slaveControl 1) I think that the problem occures everytime two event happen at the same time (here: 10:41:30,808). Does anybody has an idea how to solve my problem? I already tried to add a sleep() after the method call, but that doesn't helped ... BR, Markus Edit: logtrace 11:16:07,75511:16:07,755 1129711297 INFOINFO masterControl(192.168.2.21): string broadcast message was pushed from 1291400 to vehicle 1138272 (slaveControl 1)masterControl(192.168.2.21): vehicle 1333770 was added to slave control 1 or log 11:16:08,562 12104 INFO 11:16:08,562 masterControl(192.168.2.21): string broadcast message was pushed from 117772 to vehicle 1217744 (slaveControl 1) 12104 INFO masterControl(192.168.2.21): vehicle 1169775 was pushed to slave control 1 Edit 2: It seems like the problem only occurs if logging methods are called from inside a RMI thread (my client / server exchange information using RMI connections). ... Edit 3: I solved the problem by myself: It seems like log4j is NOT completely thread-save. After synchronizing all log / trace methods using a separate object everything is working fine. Maybe the lib is writing the messages to a thread-unsafe buffer before writing them to file?

    Read the article

  • Problems with createImage(int width, int height)

    - by Jonathan
    I have the following code, which is run every 10ms as part of a game: private void gameRender() { if(dbImage == null) { //createImage() returns null if GraphicsEnvironment.isHeadless() //returns true. (java.awt.GraphicsEnvironment) dbImage = createImage(PWIDTH, PHEIGHT); if(dbImage == null) { System.out.println("dbImage is null"); //Error recieved return; } else dbg = dbImage.getGraphics(); } //clear the background dbg.setColor(Color.white); dbg.fillRect(0, 0, PWIDTH, PHEIGHT); //draw game elements... if(gameOver) { gameOverMessage(dbg); } } The problem is that it enters the if statement which checks for the Image being null, even after I attempt to define the image. I looked around, and it seems that createImage() will return null if GraphicsEnvironment.isHeadless() returns true. I don't understand exactly what the isHeadless() method's purpose is, but I thought it might have something to do with the compiler or IDE, so I tried on two, both of which get the same error (Eclipse, and BlueJ). Anyone have any idea what the source of the error is, and how I might fix it? Thanks in advance Jonathan ................................................................... EDIT: I am using java.awt.Component.createImage(int width, int height). The purpose of this method is to ensure the creation of, and edit an Image that will contain the view of the player of the game, that will later be drawn to the screen by means of a JPanel. Here is some more code if this helps at all: public class Sim2D extends JPanel implements Runnable { private static final int PWIDTH = 500; private static final int PHEIGHT = 400; private volatile boolean running = true; private volatile boolean gameOver = false; private Thread animator; //gameRender() private Graphics dbg; private Image dbImage = null; public Sim2D() { setBackground(Color.white); setPreferredSize(new Dimension(PWIDTH, PHEIGHT)); setFocusable(true); requestFocus(); //Sim2D now recieves key events readyForTermination(); addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { testPress(e.getX(), e.getY()); } }); } //end of constructor private void testPress(int x, int y) { if(!gameOver) { gameOver = true; //end game at mousepress } } //end of testPress() private void readyForTermination() { addKeyListener( new KeyAdapter() { public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if((keyCode == KeyEvent.VK_ESCAPE) || (keyCode == KeyEvent.VK_Q) || (keyCode == KeyEvent.VK_END) || ((keyCode == KeyEvent.VK_C) && e.isControlDown()) ) { running = false; //end process on above list of keypresses } } }); } //end of readyForTermination() public void addNotify() { super.addNotify(); //creates the peer startGame(); //start the thread } //end of addNotify() public void startGame() { if(animator == null || !running) { animator = new Thread(this); animator.start(); } } //end of startGame() //run method for world public void run() { while(running) { long beforeTime, timeDiff, sleepTime; beforeTime = System.nanoTime(); gameUpdate(); //updates objects in game (step event in game) gameRender(); //renders image paintScreen(); //paints rendered image to screen timeDiff = (System.nanoTime() - beforeTime) / 1000000; sleepTime = 10 - timeDiff; if(sleepTime <= 0) //if took longer than 10ms { sleepTime = 5; //sleep a bit anyways } try{ Thread.sleep(sleepTime); //sleep by allotted time (attempts to keep this loop to about 10ms) } catch(InterruptedException ex){} beforeTime = System.nanoTime(); } System.exit(0); } //end of run() private void gameRender() { if(dbImage == null) { dbImage = createImage(PWIDTH, PHEIGHT); if(dbImage == null) { System.out.println("dbImage is null"); return; } else dbg = dbImage.getGraphics(); } //clear the background dbg.setColor(Color.white); dbg.fillRect(0, 0, PWIDTH, PHEIGHT); //draw game elements... if(gameOver) { gameOverMessage(dbg); } } //end of gameRender() } //end of class Sim2D Hope this helps clear things up a bit, Jonathan

    Read the article

  • Adjust parameters of serial port reading

    - by clinisbut
    Hello. I'm facing a particular issue that regards serial communication under win32. I'm communicating with a device can only accept frames when it is not already communicating. So I must find a valid frame and then inmediatelly send my request. I developed a class named Serial that handles basic operations on serial port (open, close, read, write) and then a Thread calls inside a loop read and write functions. Thread loop //Device is an object of class Serial while( device->isOpen() && !terminate ) { unsigned int readed = 0; unsigned long error = ERROR_SUCCESS; unsigned char* data = device->read( &readed, &error ); if( error==ERROR_SUCCESS ) { //If data received, deliver to upper level if( readed>0 ) { QByteArray output( (const char*)data, (signed int)readed ); emit dataArrived( output, readed ); } } else { //unrelated stuff } //Here I manage the writting issue //Only when nothing is received, and Upper layer wants to send a frame //(Upper layer only will mark as something to send when it detects a valid frame) if( readed==0 ) { out_lock.lock(); //If something to send... if( something_to_send > 0 ) { if( device->write( output_buffer, output_size, &error ) ) { //things... } } } } The Thread basically keeps reading, and when nothing is received, sees if somebody has signaled to send a frame (this means that a valid frame is just received). When this happens, it writes the frame through serial port. Here comes my problem. Inside the Serial::read() function: I use the overlapped way of reading: ::ClearCommError( handle, &dwErrors, &stat); if( stat.cbInQue ) { //If there's something to read, read it, please note the bytes to read parameter, here 1. bool ok = ::ReadFile( handle, buffer_in, 1, &bytes_read, &ov_reader ); if( !ok ) { DWORD _error = ::GetLastError(); if( _error == ERROR_IO_PENDING ) { DWORD result = ::WaitForMultipleObjects( 2, waiters, FALSE,INFINITE ); switch( result ) { //Eventshutdown case WAIT_OBJECT_0: /*code omitted*/break; case WAIT_OBJECT_0+1: ok = ::GetOverlappedResult( handle, &ov_reader, &bytes_read, true ); //check ok value omitted break; } } } } if( bytes_read>0 ) { *size = bytes_read; } Here starts my problem. When device sends me small frames (around 30 bytes) everything works fine, but when larger frames are sent, the code is not able to find any free time between frames causing the thread to never be able send any frame because readed is never 0. If I increase the number of bytes to read inside the read() function, lose the ability to detect when the device "listens": bool ok = ::ReadFile(handle, buffer_in, 50, &bytes_read, &ov_reader ); This happens because my app can receive the end of a frame together with the start of the next one. This behaviour is very common. In the other hand, if I change the INFINITE argument by a valid timeout in the WaitForMultipleObjects function, I lose data. So my question basically is... what I'm doing wrong? Why when reading 1 byte each time I don't find any free time to send my own frames? Thank you

    Read the article

  • non blocking client server chat application in java using nio

    - by Amith
    I built a simple chat application using nio channels. I am very much new to networking as well as threads. This application is for communicating with server (Server / Client chat application). My problem is that multiple clients are not supported by the server. How do I solve this problem? What's the bug in my code? public class Clientcore extends Thread { SelectionKey selkey=null; Selector sckt_manager=null; public void coreClient() { System.out.println("please enter the text"); BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in)); SocketChannel sc = null; try { sc = SocketChannel.open(); sc.configureBlocking(false); sc.connect(new InetSocketAddress(8888)); int i=0; while (!sc.finishConnect()) { } for(int ii=0;ii>-22;ii++) { System.out.println("Enter the text"); String HELLO_REQUEST =stdin.readLine().toString(); if(HELLO_REQUEST.equalsIgnoreCase("end")) { break; } System.out.println("Sending a request to HelloServer"); ByteBuffer buffer = ByteBuffer.wrap(HELLO_REQUEST.getBytes()); sc.write(buffer); } } catch (IOException e) { e.printStackTrace(); } finally { if (sc != null) { try { sc.close(); } catch (Exception e) { e.printStackTrace(); } } } } public void run() { try { coreClient(); } catch(Exception ej) { ej.printStackTrace(); }}} public class ServerCore extends Thread { SelectionKey selkey=null; Selector sckt_manager=null; public void run() { try { coreServer(); } catch(Exception ej) { ej.printStackTrace(); } } private void coreServer() { try { ServerSocketChannel ssc = ServerSocketChannel.open(); try { ssc.socket().bind(new InetSocketAddress(8888)); while (true) { sckt_manager=SelectorProvider.provider().openSelector(); ssc.configureBlocking(false); SocketChannel sc = ssc.accept(); register_server(ssc,SelectionKey.OP_ACCEPT); if (sc == null) { } else { System.out.println("Received an incoming connection from " + sc.socket().getRemoteSocketAddress()); printRequest(sc); System.err.println("testing 1"); String HELLO_REPLY = "Sample Display"; ByteBuffer buffer = ByteBuffer.wrap(HELLO_REPLY.getBytes()); System.err.println("testing 2"); sc.write(buffer); System.err.println("testing 3"); sc.close(); }}} catch (IOException e) { e.printStackTrace(); } finally { if (ssc != null) { try { ssc.close(); } catch (IOException e) { e.printStackTrace(); } } } } catch(Exception E) { System.out.println("Ex in servCORE "+E); } } private static void printRequest(SocketChannel sc) throws IOException { ReadableByteChannel rbc = Channels.newChannel(sc.socket().getInputStream()); WritableByteChannel wbc = Channels.newChannel(System.out); ByteBuffer b = ByteBuffer.allocate(1024); // read 1024 bytes while (rbc.read(b) != -1) { b.flip(); while (b.hasRemaining()) { wbc.write(b); System.out.println(); } b.clear(); } } public void register_server(ServerSocketChannel ssc,int selectionkey_ops)throws Exception { ssc.register(sckt_manager,selectionkey_ops); }} public class HelloClient { public void coreClientChat() { Clientcore t=new Clientcore(); new Thread(t).start(); } public static void main(String[] args)throws Exception { HelloClient cl= new HelloClient(); cl.coreClientChat(); }} public class HelloServer { public void coreServerChat() { ServerCore t=new ServerCore(); new Thread(t).start(); } public static void main(String[] args) { HelloServer st= new HelloServer(); st.coreServerChat(); }}

    Read the article

  • Android Frame based animation memory problem

    - by madsleejensen
    Hi all Im trying to create a animation on top of a Camera Surface view. The animation if a box rotating, and to enable transparency i made a bunch of *.png files that i want to just switch out on top of the Camera view. The problem is Android wont allow me to allocate so many images (too much memory required) so the AnimationDrawable is not an option. Will i be able to allocate all the *.png bitmaps if i use OpenGL instead? then i would store all the *.png's as Textures and just make my own animation logic? is am i under the same restrictions there? Any ideas on how to solve this problem ? Ive made a Custom view that loads the image resource on every frame and discards it when next frame is to be displayed. But the performance is terrible. import android.app.Activity; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.SystemClock; import android.util.Log; import android.widget.ImageView; public class FrameAnimationView extends ImageView { private int mFramesPerSecond = 10; private int mTimeBetweenFrames = (1000 / mFramesPerSecond); private int mCurrentFrame = 1; private String[] mFrames; private Thread mAnimationThread; private Resources mResources; private String mIdentifierPrefix; private Activity mContext; private boolean mIsAnimating = false; private Integer[] mDrawableIndentifiers; public FrameAnimationView(Activity context, String[] frames) { super(context); mContext = context; mResources = context.getResources(); mFrames = frames; mIdentifierPrefix = context.getPackageName() + ":drawable/"; mDrawableIndentifiers = new Integer[frames.length]; } private void initAnimationThread() { mAnimationThread = new Thread(new Runnable() { @Override public void run() { while (mIsAnimating) { final int frameToShow = (mCurrentFrame - 1); //Log.e("frame", Integer.toString(frameToShow)); mContext.runOnUiThread(new Runnable() { @Override public void run() { if (mDrawableIndentifiers[frameToShow] == null) { String frameId = mFrames[frameToShow]; int drawableResourceId = mResources.getIdentifier(mIdentifierPrefix + frameId, null, null); mDrawableIndentifiers[frameToShow] = drawableResourceId; } Drawable frame = getResources().getDrawable(mDrawableIndentifiers[frameToShow]); setBackgroundDrawable(frame); if (mCurrentFrame < mFrames.length) { mCurrentFrame++; } else { mCurrentFrame = 1; } } }); try { Thread.sleep(mTimeBetweenFrames); } catch (InterruptedException e) { e.printStackTrace(); } } } }); } public void setFramesPerSecond(int fps) { mFramesPerSecond = fps; mTimeBetweenFrames = (1000 / mFramesPerSecond); } public void startAnimation() { if (mIsAnimating) return; mIsAnimating = true; initAnimationThread(); mAnimationThread.start(); } public void stopAnimation() { if (mIsAnimating) { Thread oldThread = mAnimationThread; mAnimationThread = null; oldThread.interrupt(); mIsAnimating = false; } } }

    Read the article

  • android ftp upload has stopped error

    - by Goxel Arp
    class Asenkron extends AsyncTask<String,Integer,Long> { @Override protected Long doInBackground(String... aurl) { FTPClient con=null; try ` { con = new FTPClient(); con.connect(aurl[0]); if (con.login(aurl[1], aurl[2])) { con.enterLocalPassiveMode(); // important! con.setFileType(http://FTP.BINARY_FILE_TYPE); FileInputStream in = new FileInputStream(new File(aurl[3])); boolean result = con.storeFile(aurl[3], in); in.close(); con.logout(); con.disconnect(); } } catch (Exception e) { Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show(); } return null; } protected void onPostExecute(String result) {} } I AM USING THIS CLASS LIKE BELOW.THERE IS BUTTON AND WHENEVER I CLICK THE BUTTON IT SHOULD START FTP UPLOAD PROCESS IN BACKGROUND BUT I GET "PROGRAM HAS STOPPED UNFORTUNATELY" ERROR. Assume that The ftp address and username password pathfile sections are true and I get the internet and network permissions already by the way ... button1.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { new Asenkron().execute("ftpaddress","username","pass","pathfileon telephone"); } }); And here is the logcat for you to analyse the potential error and help me ... 10-13 13:01:25.591: I/dalvikvm(633): threadid=3: reacting to signal 3 10-13 13:01:25.711: I/dalvikvm(633): Wrote stack traces to '/data/anr/traces.txt' 10-13 13:01:25.921: D/gralloc_goldfish(633): Emulator without GPU emulation detected. 10-13 13:01:31.441: W/dalvikvm(633): threadid=11: thread exiting with uncaught exception (group=0x409c01f8) 10-13 13:01:31.461: E/AndroidRuntime(633): FATAL EXCEPTION: AsyncTask #1 10-13 13:01:31.461: E/AndroidRuntime(633): java.lang.RuntimeException: An error occured while executing doInBackground() 10-13 13:01:31.461: E/AndroidRuntime(633): at android.os.AsyncTask$3.done(AsyncTask.java:278) 10-13 13:01:31.461: E/AndroidRuntime(633): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 10-13 13:01:31.461: E/AndroidRuntime(633): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 10-13 13:01:31.461: E/AndroidRuntime(633): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 10-13 13:01:31.461: E/AndroidRuntime(633): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 10-13 13:01:31.461: E/AndroidRuntime(633): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208) 10-13 13:01:31.461: E/AndroidRuntime(633): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 10-13 13:01:31.461: E/AndroidRuntime(633): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 10-13 13:01:31.461: E/AndroidRuntime(633): at java.lang.Thread.run(Thread.java:856) 10-13 13:01:31.461: E/AndroidRuntime(633): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 10-13 13:01:31.461: E/AndroidRuntime(633): at android.os.Handler.<init>(Handler.java:121) 10-13 13:01:31.461: E/AndroidRuntime(633): at android.widget.Toast$TN.<init>(Toast.java:317) 10-13 13:01:31.461: E/AndroidRuntime(633): at android.widget.Toast.<init>(Toast.java:91) 10-13 13:01:31.461: E/AndroidRuntime(633): at android.widget.Toast.makeText(Toast.java:233) 10-13 13:01:31.461: E/AndroidRuntime(633): at com.example.ftpodak.ODAK$Asenkron.doInBackground(ODAK.java:74) 10-13 13:01:31.461: E/AndroidRuntime(633): at com.example.ftpodak.ODAK$Asenkron.doInBackground(ODAK.java:1) 10-13 13:01:31.461: E/AndroidRuntime(633): at android.os.AsyncTask$2.call(AsyncTask.java:264) 10-13 13:01:31.461: E/AndroidRuntime(633): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 10-13 13:01:31.461: E/AndroidRuntime(633): ... 5 more By the way I changed the relevant code like that ; instead of catch (Exception e) { Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show(); } I replaced with this code catch (Exception e) { HATA=e.toString(); } And I added the code to button textview1.setText(HATA); So I can see the error on the textview and it is writing that "Android java.net.UnknownHostException: Host is unresolved" But i know that the ftp server is correct and I check the ftp server from the AndFTP application. With the same address login and pass information ftp server is working.So the problem is in my code I think.Any help will be too much appreciated.Anyone who can help me I can give teamviewer to analyse what is the problem ...

    Read the article

  • Handling a Long Running jsp request on the server using Ajax and threads

    - by John Blue
    I am trying to implement a solution for a long running process on the server where it is taking about 10 min to process a pdf generation request. The browser bored/timesout at the 5 mins. I was thinking to deal with this using a Ajax and threads. I am using regular javascript for ajax. But I am stuck with it. I have reached till the point where it sends the request to the servlet and the servlet starts the thread.Please see the below code public class HelloServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("POST request!!"); LongProcess longProcess = new LongProcess(); longProcess.setDaemon(true); longProcess.start(); request.getSession().setAttribute("longProcess", longProcess); request.getRequestDispatcher("index.jsp").forward(request, response); } } class LongProcess extends Thread { public void run() { System.out.println("Thread Started!!"); while (progress < 10) { try { sleep(2000); } catch (InterruptedException ignore) {} progress++; } } } Here is my AJax call <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html><head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>My Title</title> <script language="JavaScript" > function getXMLObject() //XML OBJECT { var xmlHttp = false; xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers return xmlHttp; // Mandatory Statement returning the ajax object created } var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object function ajaxFunction() { xmlhttp.open("GET","HelloServlet" ,true); xmlhttp.onreadystatechange = handleServerResponse; xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlhttp.send(null); } function handleServerResponse() { if (xmlhttp.readyState == 4) { if(xmlhttp.status == 200) { document.forms[0].myDiv.value = xmlhttp.responseText; setTimeout(ajaxFunction(), 2000); } else { alert("Error during AJAX call. Please try again"); } } } function openPDF() { document.forms[0].method = "POST"; document.forms[0].action = "HelloServlet"; document.forms[0].submit(); } function stopAjax(){ clearInterval(intervalID); } </script> </head> <body><form name="myForm"> <table><tr><td> <INPUT TYPE="BUTTON" NAME="Download" VALUE="Download Queue ( PDF )" onclick="openPDF();"> </td></tr> <tr><td> Current status: <div id="myDiv"></div>% </td></tr></table> </form></body></html> But I dont know how to proceed further like how will the thread communicate the browser that the process has complete and how should the ajax call me made and check the status of the request. Please let me know if I am missing some pieces. Any suggestion if helpful.

    Read the article

  • Problems with Asynchronous UDP Sockets

    - by ihatenetworkcoding
    Hi, I'm struggling a bit with socket programming (something I'm not at all familiar with) and I can't find anything which helps from google or MSDN (awful). Apologies for the length of this. Basically I have an existing service which recieves and responds to requests over UDP. I can't change this at all. I also have a client within my webapp which dispatches and listens for responses to that service. The existing client I've been given is a singleton which creates a socket and an array of response slots, and then creates a background thread with an infinite looping method that makes "sock.Receive()" calls and pushes the data received into the slot array. All kinds of things about this seem wrong to me and the infinite thread breaks my unit testing so I'm trying to replace this service with one which makes it's it's send/receives asynchronously instead. Point 1: Is this the right approach? I want a non-blocking, scalable, thread-safe service. My first attempt is roughly like this, which sort of worked but the data I got back was always shorter than expected (i.e. the buffer did not have the number of bytes requested) and seemed to throw exceptions when processed. private Socket MyPreConfiguredSocket; public object Query() { //build a request this.MyPreConfiguredSocket.SendTo(MYREQUEST, packet.Length, SocketFlags.Multicast, this._target); IAsyncResult h = this._sock.BeginReceiveFrom(response, 0, BUFFER_SIZE, SocketFlags.None, ref this._target, new AsyncCallback(ARecieve), this._sock); if (!h.AsyncWaitHandle.WaitOne(TIMEOUT)) { throw new Exception("Timed out"); } //process response data (always shortened) } private void ARecieve (IAsyncResult result) { int bytesreceived = (result as Socket).EndReceiveFrom(result, ref this._target); } My second attempt was based on more google trawling and this recursive pattern I frequently saw, but this version always times out! It never gets to ARecieve. public object Query() { //build a request this.MyPreConfiguredSocket.SendTo(MYREQUEST, packet.Length, SocketFlags.Multicast, this._target); State s = new State(this.MyPreConfiguredSocket); this.MyPreConfiguredSocket.BeginReceiveFrom(s.Buffer, 0, BUFFER_SIZE, SocketFlags.None, ref this._target, new AsyncCallback(ARecieve), s); if (!s.Flag.WaitOne(10000)) { throw new Exception("Timed out"); } //always thrown //process response data } private void ARecieve (IAsyncResult result) { //never gets here! State s = (result as State); int bytesreceived = s.Sock.EndReceiveFrom(result, ref this._target); if (bytesreceived > 0) { s.Received += bytesreceived; this._sock.BeginReceiveFrom(s.Buffer, s.Received, BUFFER_SIZE, SocketFlags.None, ref this._target, new AsyncCallback(ARecieve), s); } else { s.Flag.Set(); } } private class State { public State(Socket sock) { this._sock = sock; this._buffer = new byte[BUFFER_SIZE]; this._buffer.Initialize(); } public Socket Sock; public byte[] Buffer; public ManualResetEvent Flag = new ManualResetEvent(false); public int Received = 0; } Point 2: So clearly I'm getting something quite wrong. Point 3: I'm not sure if I'm going about this right. How does the data coming from the remote service even get to the right listening thread? Do I need to create a socket per request? Out of my comfort zone here. Need help.

    Read the article

  • Hibernate/Spring: failed to lazily initialize - no session or session was closed

    - by Niko
    I know something similar has been asked already, but unfortunately I wasn't able to find a reliable answer - even with searching for over 2 days. The basic problem is the same as asked multiple time. I have a simple program with two POJOs Event and User - where a user can have multiple events. @Entity @Table public class Event { private Long id; private String name; private User user; @Column @Id @GeneratedValue public Long getId() {return id;} public void setId(Long id) { this.id = id; } @Column public String getName() {return name;} public void setName(String name) {this.name = name;} @ManyToOne @JoinColumn(name="user_id") public User getUser() {return user;} public void setUser(User user) {this.user = user;} } @Entity @Table public class User { private Long id; private String name; private List events; @Column @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany(mappedBy="user", fetch=FetchType.LAZY) public List getEvents() { return events; } public void setEvents(List events) { this.events = events; } } Note: This is a sample project. I really want to use Lazy fetching here. I use spring and hibernate and have a simple basic-db.xml for loading: <?xml version="1.0" encoding="UTF-8"? <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" scope="thread" <property name="driverClassName" value="com.mysql.jdbc.Driver" / <property name="url" value="jdbc:mysql://192.168.1.34:3306/hibernateTest" / <property name="username" value="root" / <property name="password" value="" / <aop:scoped-proxy/ </bean <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer" <property name="scopes" <map <entry key="thread" <bean class="org.springframework.context.support.SimpleThreadScope" / </entry </map </property </bean <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" scope="thread" <property name="dataSource" ref="myDataSource" / <property name="annotatedClasses" <list <valuedata.model.User</value <valuedata.model.Event</value </list </property <property name="hibernateProperties" <props <prop key="hibernate.dialect"org.hibernate.dialect.MySQLDialect</prop <prop key="hibernate.show_sql"true</prop <prop key="hibernate.hbm2ddl.auto"create</prop </props </property <aop:scoped-proxy/ </bean <bean id="myUserDAO" class="data.dao.impl.UserDaoImpl" <property name="sessionFactory" ref="mySessionFactory" / </bean <bean id="myEventDAO" class="data.dao.impl.EventDaoImpl" <property name="sessionFactory" ref="mySessionFactory" / </bean </beans Note: I played around with the CustomScopeConfigurer and SimpleThreadScope, but that didnt change anything. I have a simple dao-impl (only pasting the userDao - the EventDao is pretty much the same - except with out the "listWith" function: public class UserDaoImpl implements UserDao{ private HibernateTemplate hibernateTemplate; public void setSessionFactory(SessionFactory sessionFactory) { this.hibernateTemplate = new HibernateTemplate(sessionFactory); } @SuppressWarnings("unchecked") @Override public List listUser() { return hibernateTemplate.find("from User"); } @Override public void saveUser(User user) { hibernateTemplate.saveOrUpdate(user); } @Override public List listUserWithEvent() { List users = hibernateTemplate.find("from User"); for (User user : users) { System.out.println("LIST : " + user.getName() + ":"); user.getEvents().size(); } return users; } } I am getting the org.hibernate.LazyInitializationException - failed to lazily initialize a collection of role: data.model.User.events, no session or session was closed at the line with user.getEvents().size(); And last but not least here is the Test class I use: public class HibernateTest { public static void main(String[] args) { ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("basic-db.xml"); UserDao udao = (UserDao) ac.getBean("myUserDAO"); EventDao edao = (EventDao) ac.getBean("myEventDAO"); System.out.println("New user..."); User user = new User(); user.setName("test"); Event event1 = new Event(); event1.setName("Birthday1"); event1.setUser(user); Event event2 = new Event(); event2.setName("Birthday2"); event2.setUser(user); udao.saveUser(user); edao.saveEvent(event1); edao.saveEvent(event2); List users = udao.listUserWithEvent(); System.out.println("Events for users"); for (User u : users) { System.out.println(u.getId() + ":" + u.getName() + " --"); for (Event e : u.getEvents()) { System.out.println("\t" + e.getId() + ":" + e.getName()); } } ((ConfigurableApplicationContext)ac).close(); } } and here is the Exception I get: 1621 [main] ERROR org.hibernate.LazyInitializationException - failed to lazily initialize a collection of role: data.model.User.events, no session or session was closed org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: data.model.User.events, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:380) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:372) at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:119) at org.hibernate.collection.PersistentBag.size(PersistentBag.java:248) at data.dao.impl.UserDaoImpl.listUserWithEvent(UserDaoImpl.java:38) at HibernateTest.main(HibernateTest.java:44) Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: data.model.User.events, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:380) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:372) at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:119) at org.hibernate.collection.PersistentBag.size(PersistentBag.java:248) at data.dao.impl.UserDaoImpl.listUserWithEvent(UserDaoImpl.java:38) at HibernateTest.main(HibernateTest.java:44) Things I tried but did not work: assign a threadScope and using beanfactory (I used "request" or "thread" - no difference noticed): // scope stuff Scope threadScope = new SimpleThreadScope(); ConfigurableListableBeanFactory beanFactory = ac.getBeanFactory(); beanFactory.registerScope("request", threadScope); ac.refresh(); ... Setting up a transaction by getting the session object from the deo: ... Transaction tx = ((UserDaoImpl)udao).getSession().beginTransaction(); tx.begin(); users = udao.listUserWithEvent(); ... getting a transaction within the listUserWithEvent() public List listUserWithEvent() { SessionFactory sf = hibernateTemplate.getSessionFactory(); Session s = sf.openSession(); Transaction tx = s.beginTransaction(); tx.begin(); List users = hibernateTemplate.find("from User"); for (User user : users) { System.out.println("LIST : " + user.getName() + ":"); user.getEvents().size(); } tx.commit(); return users; } I am really out of ideas by now. Also, using the listUser or listEvent just work fine.

    Read the article

  • Long-running ASP.NET tasks

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

    Read the article

  • Mercurial on IIS7 connection timeout.

    - by Ronnie
    I configured Mercurial on IIS 7 and I am able tu push and pull without problems some test files. If I try tu push a bigger repository I get for the hg push command line this error : abort: error: An existing connection was forcibly closed by the remote host From Tortoise HG I get some more detail: lopen error [Errno 10054] An existing connection was forcibly closed by the remote host Is seemed to me some kind of connection timeout for the CGI but I extended the cgi timeout properties in IIS7 configuration. What could be the problem?

    Read the article

  • hpricot segfault?

    - by AP257
    Any idea why hpricot might segfault on this page? trial_url = 'http://www.controlled-trials.com/ISRCTN56071145/' doc = Hpricot(open(trial_url)) produces: /Users/ap257/.gem/ruby/1.8/gems/hpricot-0.8.2/lib/hpricot/parse.rb:33: [BUG] Segmentation fault ruby 1.8.7 (2009-06-08 patchlevel 173) [universal-darwin10.0] Abort trap Please could anyone advise on how I could get around this, or whether it's a bug in hpricot that I should report somewhere? Thanks!

    Read the article

  • Accurately display upload progress in Silverilght upload

    - by Matt
    I'm trying to debug a file upload / download issue I'm having. I've got a Silverlight file uploader, and to transmit the files I make use of the HttpWebRequest class. So I create a connection to my file upload handler on the server and begin transmitting. While a file uploads I keep track of total bytes written to the RequestStream so I can figure out a percentage. Now working at home I've got a rather slow connection, and I think Silverlight, or the browser, is lying to me. It seems that my upload progress logic is inaccurate. When I do multiple file uploads (24 images of 3-6mb big in my testing), the logic reports the files finish uploading but I believe that it only reflects the progress of written bytes to the RequestStream, not the actual amount of bytes uploaded. What is the most accurate way to measure upload progress. Here's the logic I'm using. public void Upload() { if( _TargetFile != null ) { Status = FileUploadStatus.Uploading; Abort = false; long diff = _TargetFile.Length - BytesUploaded; UriBuilder ub = new UriBuilder( App.siteUrl + "upload.ashx" ); bool complete = diff <= ChunkSize; ub.Query = string.Format( "{3}name={0}&StartByte={1}&Complete={2}", fileName, BytesUploaded, complete, string.IsNullOrEmpty( ub.Query ) ? "" : ub.Query.Remove( 0, 1 ) + "&" ); HttpWebRequest webrequest = ( HttpWebRequest ) WebRequest.Create( ub.Uri ); webrequest.Method = "POST"; webrequest.BeginGetRequestStream( WriteCallback, webrequest ); } } private void WriteCallback( IAsyncResult asynchronousResult ) { HttpWebRequest webrequest = ( HttpWebRequest ) asynchronousResult.AsyncState; // End the operation. Stream requestStream = webrequest.EndGetRequestStream( asynchronousResult ); byte[] buffer = new Byte[ 4096 ]; int bytesRead = 0; int tempTotal = 0; Stream fileStream = _TargetFile.OpenRead(); fileStream.Position = BytesUploaded; while( ( bytesRead = fileStream.Read( buffer, 0, buffer.Length ) ) != 0 && tempTotal + bytesRead < ChunkSize && !Abort ) { requestStream.Write( buffer, 0, bytesRead ); requestStream.Flush(); BytesUploaded += bytesRead; tempTotal += bytesRead; int percent = ( int ) ( ( BytesUploaded / ( double ) _TargetFile.Length ) * 100 ); UploadPercent = percent; if( UploadProgressChanged != null ) { UploadProgressChangedEventArgs args = new UploadProgressChangedEventArgs( percent, bytesRead, BytesUploaded, _TargetFile.Length, _TargetFile.Name ); SmartDispatcher.BeginInvoke( () => UploadProgressChanged( this, args ) ); } } //} // only close the stream if it came from the file, don't close resizestream so we don't have to resize it over again. fileStream.Close(); requestStream.Close(); webrequest.BeginGetResponse( ReadCallback, webrequest ); }

    Read the article

  • How to parametrize a test using cppunit

    - by Harald Scheirich
    We are using cppunit, i am trying to run the same test using different parameters, running a loop inside the test is not a good option as any failure will abort the test. I have looked at TestDecorator and TestCaller but neither seem to really fit. Code samples would be helpful. Thanks.

    Read the article

  • Storing a remote path by name in Hg

    - by Erik Vold
    In git I can git remote add x http://... then git pull x how can I do this in hg? I was told to add the following to .hgrc: [paths] x = http://... so I added the above to /path/to/repo/.hgrc then tried hg pull x and got the following error: abort: repository x not found! where x was mozilla and http:// was http://hg.mozilla.org/labs/jetpack-sdk/

    Read the article

  • Ideal way to cancel an executing AsyncTask

    - by Samuh
    I am running remote audio-file-fetching and audio file playback operations in a background thread using AsyncTask. A Cancellable progress bar is shown for the time the fetch operation runs. I want to cancel/abort the AsyncTask run when the user cancels (decides against) the operation. What is the ideal way to handle such a case?

    Read the article

  • How do you cancel an external git diff?

    - by v2k
    I've got vim setup as my external diff tool: [diff] external = git_diff_wrapper !/bin/sh vimdiff "$2" "$5" Say I have 300 files that have been modified; via bash, I type "git diff". It launches 300 vimdiffs sequentially, how do I abort it?

    Read the article

  • Ideal way to cancel an executing AsnycTask

    - by Samuh
    I am running remote audio-file-fetching and audio file playback operations in a background thread using AsnycTask. A Cancellable progress bar is shown for the time the fetch operation runs. I want to cancel/abort the AsnycTask run when the user cancels(decides against) the operation. What is the ideal way to handle such a case? Thanks.

    Read the article

  • Heap Consistency Checking on Embedded System

    - by l.thee.a
    I get a crash like this: #0 0x2c58def0 in raise () from /lib/libpthread.so.0 #1 0x2d9b8958 in abort () from /lib/libc.so.0 #2 0x2d9b7e34 in __malloc_consolidate () from /lib/libc.so.0 #3 0x2d9b6dc8 in malloc () from /lib/libc.so.0 I guess it is a heap corruption issue. uclibc does not have mcheck/mprobe. Valgrind does not seem to MIPS support and my app (which is multi-threaded) depends on hw specific drivers. Any suggestions to check the consistency of the heap and to detect corruption?

    Read the article

  • C++ Program Always Crashes While doing a std::string assign

    - by bbazso
    I have been trying to debug a crash in my application that crashes (i.e. asserts a * glibc detected free(): invalid pointer: 0x000000000070f0c0 **) while I'm trying to do a simple assign to a string. Note that I'm compiling on a linux system with gcc 4.2.4 with an optimization level set to -O2. With -O0 the application no longer crashes. E.g. std::string abc; abc = "testString"; but if I changed the code as follows it no longer crashes std::string abc("testString"); So again I scratched my head! But the interesting pattern was that the crash moved later on in the application, AGAIN at another string. I found it weird that the application was continuously crashing on a string assign. A typical crash backtrace would look as follows: #0 0x00007f2c2663bfb5 in raise () from /lib64/libc.so.6 (gdb) bt #0 0x00007f2c2663bfb5 in raise () from /lib64/libc.so.6 #1 0x00007f2c2663dbc3 in abort () from /lib64/libc.so.6 #2 0x00000000004d8cb7 in people_streamingserver_sighandler (signum=6) at src/peoplestreamingserver.cpp:487 #3 <signal handler called> #4 0x00007f2c2663bfb5 in raise () from /lib64/libc.so.6 #5 0x00007f2c2663dbc3 in abort () from /lib64/libc.so.6 #6 0x00007f2c26680ce0 in ?? () from /lib64/libc.so.6 #7 0x00007f2c270ca7a0 in std::string::assign (this=0x7f2c21bc8d20, __str=<value optimized out>) at /home/bbazso/ThirdParty/sources/gcc-4.2.4/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/basic_string.h:238 #8 0x00007f2c21bd874a in PEOPLESProtocol::GetStreamName (this=<value optimized out>, pRawPath=0x2342fd8 "rtmp://127.0.0.1/mp4:pop.mp4", lStreamName=@0x7f2c21bc8d20) at /opt/trx-HEAD/gcc/4.2.4/lib/gcc/x86_64-pc-linux-gnu/4.2.4/../../../../include/c++/4.2.4/bits/basic_string.h:491 #9 0x00007f2c21bd9daa in PEOPLESProtocol::SignalProtocolCreated (pProtocol=0x233a4e0, customParameters=@0x7f2c21bc8de0) at peoplestreamer/src/peoplesprotocol.cpp:240 This was really weird behavior and so I started to poke around further in my application to see if there was some sort of memory corruption (either heap or stack) error that could be occurring that could be causing this weird behavior. I even checked for ptr corruptions and came up empty handed. In addition to visual inspection of the code I also tried the following tools: Valgrind using both memcheck and exp-ptrcheck electric fence libsafe I compiled with -fstack-protector-all in gcc I tried MALLOC_CHECK_ set to 2 I ran my code through lint checks as well as cppcheck (to check for mistakes) And I stepped through the code using gdb So I tried a lot of stuff and still came up empty handed. So I was wondering if it could be something like a linker issue or a library issue of some sort that could be causing this problem. Are there any know issues with the std::string that make is susceptible to crashing in -O2 or maybe it has nothing to do with the optimization level? But the only pattern that I can see thus far in my problem is that it always seems to crash on a string and so I was wondering if anyone knew of any issues that my be causing this type of behavior. Thanks a lot!

    Read the article

< Previous Page | 118 119 120 121 122 123 124 125 126 127 128 129  | Next Page >