Search Results

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

Page 163/344 | < Previous Page | 159 160 161 162 163 164 165 166 167 168 169 170  | Next Page >

  • How to handle window closed in the middle of a long running operation gracefully?

    - by Marek
    We have the following method called directly from the UI thread: void DoLengthyProcessing() { DoStuff(); var items = DoMoreStuff(); //do even more stuff - 200 lines of code trimmed this.someControl.PrepareForBigThing(); //someControl is a big user control //additional 100 lines of code that access this.someControl this.someControl.Finish(items); } Many of the called methods call Application.DoEvents() (and they do so many times) (do not ask me why, this is black magic written by black magic programmers and it can not be changed because everyone is scared what the impact would be) and there is also an operation running on a background thread involved in the processing. As a result, the window is not fully nonresponsive and can be closed manually during the processing. The Dispose method of the form "releases" the someControl variable by setting it to null. As a result, in case the user closes the window during the lengthy process, a null reference exception is thrown. How to handle this gracefully without just catching and logging the exception caused by disposal? Assigning the someControl instance to a temporary variable in the beginning of the method - but the control contains many subcontrols with similar disposal scheme - sets them to null and this causes null reference exceptions in other place put if (this.IsDisposed) return; calls before every access of the someControl variable. - making the already nasty long method even longer and unreadable. in Closing event, just indicate that we should close and only hide the window. Dispose it at the end of the lengthy operation. This is not very viable because there are many other methods involved (think 20K LOC for a single control) that would need to handle this mechanism as well. How to most effectively handle window disposal (by user action) in the middle of this kind of processing?

    Read the article

  • Why is the main method not covered?

    - by Mike.Huang
    main method: public static void main(String[] args) throws Exception { if (args.length != EXPECTED_NUMBER_OF_ARGUMENTS) { System.err.println("Usage - java XFRCompiler ConfigXML PackageXML XFR"); } String configXML = args[0]; String packageXML = args[1]; String xfr = args[2]; AutoConfigCompiler compiler = new AutoConfigCompiler(); compiler.setConfigDocument(loadDocument(configXML)); compiler.setPackageInfoDoc(loadDocument(packageXML)); // compiler.setVisiblityDoc(loadDocument("VisibilityFilter.xml")); compiler.compileModel(xfr); } private static Document loadDocument(String fileName) throws Exception { TXDOMParser parser = (TXDOMParser) ParserFactory.makeParser(TXDOMParser.class.getName()); InputSource source = new InputSource(new FileInputStream(fileName)); parser.parse(source); return parser.getDocument(); } testcase: @Test public void testCompileModel() throws Exception { // construct parameters URL configFile = Thread.currentThread().getContextClassLoader().getResource("Ford_2008_Mustang_Config.xml"); URL packageFile = Thread.currentThread().getContextClassLoader().getResource("Ford_2008_Mustang_Package.xml"); File tmpFile = new File("Ford_2008_Mustang_tmp.xfr"); if(!tmpFile.exists()) { tmpFile.createNewFile(); } String[] args = new String[]{configFile.getPath(),packageFile.getPath(),tmpFile.getPath()}; try { // test main method XFRCompiler.main(args); } catch (Exception e) { assertTrue(true); } try { // test args length is less than 3 XFRCompiler.main(new String[]{"",""}); } catch (Exception e) { assertTrue(true); } tmpFile.delete(); } Coverage outputs displayed as the lines from String configXML = args[0]; in main method are not covered.

    Read the article

  • Making two Windows using CreateWindowsEx()

    - by Jamie Keeling
    Hello, I have a windows form that has a simple menu and performs a simple operation, I want to be able to create another windows form with all the functionality of a menu bar, message pump etc.. as a separate thread so I can then share the results of the operation to the second window. I.E. 1) Form A opens Form B opens as a separate thread 2)Form A performs operation 3)Form A passes results via memory to Form B 4)Form B display results I'm confused as to how to go about it, the main app runs fine but i'm not sure how to add a second window if the first one already exists. I think that using CreateWindow will allow me to make another window but again i'm not sure how to access the message pump so I can respond to certain events like WM_CREATE on the second window. I hope it makes sense. Thanks! Edit: I've attempted to make a second window and although this does compile, no windows show atall on build. ////////////////////// // WINDOWS FUNCTION // ////////////////////// LRESULT CALLBACK WindowFunc(HWND hMainWindow, UINT message, WPARAM wParam, LPARAM lParam) { //Fields WCHAR buffer[256]; struct DiceData storage; HWND hwnd; // Act on current message switch(message) { case WM_CREATE: AddMenus(hMainWindow); hwnd = CreateWindowEx( 0, "ChildWClass", (LPCTSTR) NULL, WS_CHILD | WS_BORDER | WS_VISIBLE, 0, 0, 0, 0, hMainWindow, NULL, NULL, NULL); ShowWindow(hwnd, SW_SHOW); break; Any suggestions as to why this happens?

    Read the article

  • Async task ASP.net HttpContext.Current.Items is empty - How do handle this?

    - by GuruC
    We are running a very large web application in asp.net MVC .NET 4.0. Recently we had an audit done and the performance team says that there were a lot of null reference exceptions. So I started investigating it from the dumps and event viewer. My understanding was as follows: We are using Asyn Tasks in our controllers. We rely on HttpContext.Current.Items hashtable to store a lot of Application level values. Task<Articles>.Factory.StartNew(() => { System.Web.HttpContext.Current = ControllerContext.HttpContext.ApplicationInstance.Context; var service = new ArticlesService(page); return service.GetArticles(); }).ContinueWith(t => SetResult(t, "articles")); So we are copying the context object onto the new thread that is spawned from Task factory. This context.Items is used again in the thread wherever necessary. Say for ex: public class SomeClass { internal static int StreamID { get { if (HttpContext.Current != null) { return (int)HttpContext.Current.Items["StreamID"]; } else { return DEFAULT_STREAM_ID; } } } This runs fine as long as number of parallel requests are optimal. My questions are as follows: 1. When the load is more and there are too many parallel requests, I notice that HttpContext.Current.Items is empty. I am not able to figure out a reason for this and this causes all the null reference exceptions. 2. How do we make sure it is not null ? Any workaround if present ? NOTE: I read through in StackOverflow and people have questions like HttpContext.Current is null - but in my case it is not null and its empty. I was reading one more article where the author says that sometimes request object is terminated and it may cause problems since dispose is already called on objects. I am doing a copy of Context object - its just a shallow copy and not a deep copy.

    Read the article

  • Implementing client callback functionality in WCF

    - by PoweredByOrange
    The project I'm working on is a client-server application with all services written in WCF and the client in WPF. There are cases where the server needs to push information to the client. I initially though about using WCF Duplex Services, but after doing some research online, I figured a lot of people are avoiding it for many reasons. The next thing I thought about was having the client create a host connection, so that the server could use that to make a service call to the client. The problem however, is that the application is deployed over the internet, so that approach requires configuring the firewall to allow incoming traffic and since most of the users are regular users, that might also require configuring the router to allow port forwarding, which again is a hassle for the user. My third option is that in the client, spawns a background thread which makes a call to the GetNotifications() method on server. This method on the server side then, blocks until an actual notification is created, then the thread is notified (using an AutoResetEvent object maybe?) and the information gets sent to the client. The idea is something like this: Client private void InitializeListener() { Task.Factory.StartNew(() => { while (true) { var notification = server.GetNotifications(); // Display the notification. } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } Server public NotificationObject GetNotifications() { while (true) { notificationEvent.WaitOne(); return someNotificationObject; } } private void NotificationCreated() { // Inform the client of this event. notificationEvent.Set(); } In this case, NotificationCreated() is a callback method called when the server needs to send information to the client. What do you think about this approach? Is this scalable at all?

    Read the article

  • How can I create a DOTNET COM interop assembly for Classic ASP that does not sequentially block othe

    - by Alex Waddell
    Setup -- Create a simple COM addin through DOTNET/C# that does nothing but sleep on the current thread for 5 seconds. namespace ComTest { [ComVisible(true)] [ProgId("ComTester.Tester")] [Guid("D4D0BF9C-C169-4e5f-B28B-AFA194B29340")] [ClassInterface(ClassInterfaceType.AutoDual)] public class Tester { [STAThread()] public string Test() { System.Threading.Thread.Sleep(5000); return DateTime.Now.ToString(); } } } From an ASP page, call the test component: <%@ Language=VBScript %> <%option explicit%> <%response.Buffer=false%> <% dim test set test = CreateObject("ComTester.Tester") %> <HTML> <HEAD></HEAD> <BODY> <% Response.Write(test.Test()) set test = nothing %> </BODY> </HTML> When run on a windows 2003 server, the test.asp page blocks ALL OTHER threads in the site while the COM components sleeps. How can I create a COM component for ASP that does not block all ASP worker threads?

    Read the article

  • Named pipe stalls threads?

    - by entens
    I am attempting to push updates into a process via a named pipe, but in doing so my process loop now seams to stall on while ((line = sr.ReadLine()) != null). I'm a little mystified as to what might be wrong as this is my first foray into named pipes. void RefreshThread() { using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("processPipe", PipeDirection.In)) { pipeStream.WaitForConnection(); using (StreamReader sr = new StreamReader(pipeStream)) { for (; ; ) { if (StopThread == true) { StopThread = false; return; // exit loop and terminate the thread } // push update for heartbeat int HeartbeatHandle = ItemDictionary["Info.Heartbeat"]; int HeartbeatValue = (int)Config.Items[HeartbeatHandle].Value; Config.Items[HeartbeatHandle].Value = ++HeartbeatValue; SetItemValue(HeartbeatHandle, HeartbeatValue, (short)0xC0, DateTime.Now); string line = null; while ((line = sr.ReadLine()) != null) { // line is in the format: item, value, timestamp string[] parts = line.Split(','); // push update and store value in item cache int handle = ItemDictionary[parts[0]]; object value = parts[1]; Config.Items[handle].Value = int.Parse(value); DateTime timestamp = DateTime.FromBinary(long.Parse(parts[2])); SetItemValue(handle, value, (short)0xC0, timestamp); } Thread.Sleep(500); } } } }

    Read the article

  • gcc compilations (sometimes) result in cpu underload

    - by confusedCoder
    I have a larger C++ program which starts out by reading thousands of small text files into memory and storing data in stl containers. This takes about a minute. Periodically, a compilation will exhibit behavior where that initial part of the program will run at about 22-23% CPU load. Once that step is over, it goes back to ~100% CPU. It is more likely to happen with O2 flag turned on but not consistently. It happens even less often with the -p flag which makes it almost impossible to profile. I did capture it once but the gprof output wasn't helpful - everything runs with the same relative speed just at low cpu usage. I am quite certain that this has nothing to do with multiple cores. I do have a quad-core cpu, and most of the code is multi-threaded, but I tested this issue running a single thread. Also, when I run the problematic step in multiple threads, each thread only runs at ~20% CPU. I apologize ahead of time for the vagueness of the question but I have run out of ideas as to how to troubleshoot it further, so any hints might be helpful. UPDATE: Just to make sure it's clear, the problematic part of the code does sometimes (~30-40% of the compilations) run at 100% CPU, so it's hard to buy the (otherwise reasonable) argument that I/O is the bottleneck

    Read the article

  • C# TCP Client/Server communication issue

    - by Jamie
    What i'm currently trying to do is make a very basic webchat for irc using silverlight. Basically how i'm trying to do it is have a tcp server listening for connections from silverlight. When a client connects it creates a new connection to irc and data is passed to/from the client/irc via the server application. I've gotten it to work fine for one client connection, but as soon as two (or more) clients connect multiple connections are made to irc but all data passed from the clients just goes through the latest irc connection (if that makes sense). For example Client1, Client2 and Client3 are all connected to irc, but no matter who sends data it all comes through Client3. Between the client and server app it recongises the data coming in from different clients so i believe the problems lies within the way i've connected to the irc. When the TCP server accepts a new client a new thread is made to listen to incoming data, and from there a new thread is made to connect to irc. I'm sure thats where the problem exists, but i've confused myself a lot now and am wondering if anyone can help me figure out a solution.

    Read the article

  • How to solve this problem with Python

    - by morpheous
    I am "porting" an application I wrote in C++ into Python. This is the current workflow: Application is started from the console Application parses CLI args Application reads an ini configuration file which specifies which plugins to load etc Application starts a timer Application iterates through each loaded plugin and orders them to start work. This spawns a new worker thread for the plugin The plugins carry out their work and when completed, they die When time interval (read from config file) is up, steps 5-7 is repeated iteratively Since I am new to Python (2 days and counting), the distinction between script, modules and packages are still a bit hazy to me, and I would like to seek advice from Pythonista as to how to implement the workflow described above, using Python as the programing language. In order to keep things simple, I have decided to leave out the time interval stuff out, and instead run the python script/scripts as a cron job instead. This is how I am thinking of approaching it: Encapsulate the whole application in a package which is executable (i.e. can be run from the command line with arguments. Write the plugins as modules (I think maybe its better to implement each module in a separate file?) I havent seen any examples of using threading in Python yet. Could someone provide a snippet of how I could spawn a thread to run a module. Also, I am not sure how to implement the concept of plugins in Python - any advice would be helpful - especially with a code snippet.

    Read the article

  • A generic C++ library that provides QtConcurrent functionality?

    - by Lucas
    QtConcurrent is awesome. I'll let the Qt docs speak for themselves: QtConcurrent includes functional programming style APIs for parallel list processing, including a MapReduce and FilterReduce implementation for shared-memory (non-distributed) systems, and classes for managing asynchronous computations in GUI applications. For instance, you give QtConcurrent::map() an iterable sequence and a function that accepts items of the type stored in the sequence, and that function is applied to all the items in the collection. This is done in a multi-threaded manner, with a thread pool equal to the number of logical CPU's on the system. There are plenty of other function in QtConcurrent, like filter(), filteredReduced() etc. The standard CompSci map/reduce functions and the like. I'm totally in love with this, but I'm starting work on an OSS project that will not be using the Qt framework. It's a library, and I don't want to force others to depend on such a large framework like Qt. I'm trying to keep external dependencies to a minimum (it's the decent thing to do). I'm looking for a generic C++ framework that provides me with the same/similar high-level primitives that QtConcurrent does. AFAIK boost has nothing like this (I may be wrong though). boost::thread is very low-level compared to what I'm looking for. I know C# has something very similar with their Parallel Extensions so I know this isn't a Qt-only idea. What do you suggest I use?

    Read the article

  • My kernel only works in block (0,0)

    - by ZeroDivide
    I am trying to write a simple matrixMultiplication application that multiplies two square matrices using CUDA. I am having a problem where my kernel is only computing correctly in block (0,0) of the grid. This is my invocation code: dim3 dimBlock(4,4,1); dim3 dimGrid(4,4,1); //Launch the kernel; MatrixMulKernel<<<dimGrid,dimBlock>>>(Md,Nd,Pd,Width); This is my Kernel function __global__ void MatrixMulKernel(int* Md, int* Nd, int* Pd, int Width) { const int tx = threadIdx.x; const int ty = threadIdx.y; const int bx = blockIdx.x; const int by = blockIdx.y; const int row = (by * blockDim.y + ty); const int col = (bx * blockDim.x + tx); //Pvalue stores the Pd element that is computed by the thread int Pvalue = 0; for (int k = 0; k < Width; k++) { Pvalue += Md[row * Width + k] * Nd[k * Width + col]; } __syncthreads(); //Write the matrix to device memory each thread writes one element Pd[row * Width + col] = Pvalue; } I think the problem may have something to do with memory but I'm a bit lost. What should I do to make this code work across several blocks?

    Read the article

  • Simple Physics Simulation in java not working.

    - by Static Void Main
    Dear experts, I wanted to implement ball physics and as i m newbie, i adapt the code in tutorial http://adam21.web.officelive.com/Documents/JavaPhysicsTutorial.pdf . i try to follow that as i much as i can, but i m not able to apply all physical phenomenon in code, can somebody please tell me, where i m mistaken or i m still doing some silly programming mistake. The balls are moving when i m not calling bounce method and i m unable to avail the bounce method and ball are moving towards left side instead of falling/ending on floor**, Can some body recommend me some better way or similar easy compact way to accomplish this task of applying physics on two ball or more balls with interactivity. here is code ; import java.awt.*; public class AdobeBall { protected int radius = 20; protected Color color; // ... Constants final static int DIAMETER = 40; // ... Instance variables private int m_x; // x and y coordinates upper left private int m_y; private double dx = 3.0; // delta x and y private double dy = 6.0; private double m_velocityX; // Pixels to move each time move() is called. private double m_velocityY; private int m_rightBound; // Maximum permissible x, y values. private int m_bottomBound; public AdobeBall(int x, int y, double velocityX, double velocityY, Color color1) { super(); m_x = x; m_y = y; m_velocityX = velocityX; m_velocityY = velocityY; color = color1; } public double getSpeed() { return Math.sqrt((m_x + m_velocityX - m_x) * (m_x + m_velocityX - m_x) + (m_y + m_velocityY - m_y) * (m_y + m_velocityY - m_y)); } public void setSpeed(double speed) { double currentSpeed = Math.sqrt(dx * dx + dy * dy); dx = dx * speed / currentSpeed; dy = dy * speed / currentSpeed; } public void setDirection(double direction) { m_velocityX = (int) (Math.cos(direction) * getSpeed()); m_velocityY = (int) (Math.sin(direction) * getSpeed()); } public double getDirection() { double h = ((m_x + dx - m_x) * (m_x + dx - m_x)) + ((m_y + dy - m_y) * (m_y + dy - m_y)); double a = (m_x + dx - m_x) / h; return a; } // ======================================================== setBounds public void setBounds(int width, int height) { m_rightBound = width - DIAMETER; m_bottomBound = height - DIAMETER; } // ============================================================== move public void move() { double gravAmount = 0.02; double gravDir = 90; // The direction for the gravity to be in. // ... Move the ball at the give velocity. m_x += m_velocityX; m_y += m_velocityY; // ... Bounce the ball off the walls if necessary. if (m_x < 0) { // If at or beyond left side m_x = 0; // Place against edge and m_velocityX = -m_velocityX; } else if (m_x > m_rightBound) { // If at or beyond right side m_x = m_rightBound; // Place against right edge. m_velocityX = -m_velocityX; } if (m_y < 0) { // if we're at top m_y = 0; m_velocityY = -m_velocityY; } else if (m_y > m_bottomBound) { // if we're at bottom m_y = m_bottomBound; m_velocityY = -m_velocityY; } // double speed = Math.sqrt((m_velocityX * m_velocityX) // + (m_velocityY * m_velocityY)); // ...Friction stuff double fricMax = 0.02; // You can use any number, preferably less than 1 double friction = getSpeed(); if (friction > fricMax) friction = fricMax; if (m_velocityX >= 0) { m_velocityX -= friction; } if (m_velocityX <= 0) { m_velocityX += friction; } if (m_velocityY >= 0) { m_velocityY -= friction; } if (m_velocityY <= 0) { m_velocityY += friction; } // ...Gravity stuff m_velocityX += Math.cos(gravDir) * gravAmount; m_velocityY += Math.sin(gravDir) * gravAmount; } public Color getColor() { return color; } public void setColor(Color newColor) { color = newColor; } // ============================================= getDiameter, getX, getY public int getDiameter() { return DIAMETER; } public double getRadius() { return radius; // radius should be a local variable in Ball. } public int getX() { return m_x; } public int getY() { return m_y; } } using adobeBall: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AdobeBallImplementation implements Runnable { private static final long serialVersionUID = 1L; private volatile boolean Play; private long mFrameDelay; private JFrame frame; private MyKeyListener pit; /** true means mouse was pressed in ball and still in panel. */ private boolean _canDrag = false; private static final int MAX_BALLS = 50; // max number allowed private int currentNumBalls = 2; // number currently active private AdobeBall[] ball = new AdobeBall[MAX_BALLS]; public AdobeBallImplementation(Color ballColor) { frame = new JFrame("simple gaming loop in java"); frame.setSize(400, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pit = new MyKeyListener(); pit.setPreferredSize(new Dimension(400, 400)); frame.setContentPane(pit); ball[0] = new AdobeBall(34, 150, 7, 2, Color.YELLOW); ball[1] = new AdobeBall(50, 50, 5, 3, Color.BLUE); frame.pack(); frame.setVisible(true); frame.setBackground(Color.white); start(); frame.addMouseListener(pit); frame.addMouseMotionListener(pit); } public void start() { Play = true; Thread t = new Thread(this); t.start(); } public void stop() { Play = false; } public void run() { while (Play == true) { // bounce(ball[0],ball[1]); runball(); pit.repaint(); try { Thread.sleep(mFrameDelay); } catch (InterruptedException ie) { stop(); } } } public void drawworld(Graphics g) { for (int i = 0; i < currentNumBalls; i++) { g.setColor(ball[i].getColor()); g.fillOval(ball[i].getX(), ball[i].getY(), 40, 40); } } public double pointDistance (double x1, double y1, double x2, double y2) { return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); } public void runball() { while (Play == true) { try { for (int i = 0; i < currentNumBalls; i++) { for (int j = 0; j < currentNumBalls; j++) { if (pointDistance(ball[i].getX(), ball[i].getY(), ball[j].getX(), ball[j].getY()) < ball[i] .getRadius() + ball[j].getRadius() + 2) { // bounce(ball[i],ball[j]); ball[i].setBounds(pit.getWidth(), pit.getHeight()); ball[i].move(); pit.repaint(); } } } try { Thread.sleep(50); } catch (Exception e) { System.exit(0); } } catch (Exception e) { e.printStackTrace(); } } } public static double pointDirection(int x1, int y1, int x2, int y2) { double H = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); // The // hypotenuse double x = x2 - x1; // The opposite double y = y2 - y1; // The adjacent double angle = Math.acos(x / H); angle = angle * 57.2960285258; if (y < 0) { angle = 360 - angle; } return angle; } public static void bounce(AdobeBall b1, AdobeBall b2) { if (b2.getSpeed() == 0 && b1.getSpeed() == 0) { // Both balls are stopped. b1.setDirection(pointDirection(b1.getX(), b1.getY(), b2.getX(), b2 .getY())); b2.setDirection(pointDirection(b2.getX(), b2.getY(), b1.getX(), b1 .getY())); b1.setSpeed(1); b2.setSpeed(1); } else if (b2.getSpeed() == 0 && b1.getSpeed() != 0) { // B1 is moving. B2 is stationary. double angle = pointDirection(b1.getX(), b1.getY(), b2.getX(), b2 .getY()); b2.setSpeed(b1.getSpeed()); b2.setDirection(angle); b1.setDirection(angle - 90); } else if (b1.getSpeed() == 0 && b2.getSpeed() != 0) { // B1 is moving. B2 is stationary. double angle = pointDirection(b2.getX(), b2.getY(), b1.getX(), b1 .getY()); b1.setSpeed(b2.getSpeed()); b1.setDirection(angle); b2.setDirection(angle - 90); } else { // Both balls are moving. AdobeBall tmp = b1; double angle = pointDirection(b2.getX(), b2.getY(), b1.getX(), b1 .getY()); double origangle = b1.getDirection(); b1.setDirection(angle + origangle); angle = pointDirection(tmp.getX(), tmp.getY(), b2.getX(), b2.getY()); origangle = b2.getDirection(); b2.setDirection(angle + origangle); } } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { new AdobeBallImplementation(Color.red); } }); } } *EDIT:*ok splitting the code using new approach for gravity from this forum: this code also not working the ball is not coming on floor: public void mymove() { m_x += m_velocityX; m_y += m_velocityY; if (m_y + m_bottomBound > 400) { m_velocityY *= -0.981; // setY(400 - m_bottomBound); m_y = 400 - m_bottomBound; } // ... Bounce the ball off the walls if necessary. if (m_x < 0) { // If at or beyond left side m_x = 0; // Place against edge and m_velocityX = -m_velocityX; } else if (m_x > m_rightBound) { // If at or beyond right side m_x = m_rightBound - 20; // Place against right edge. m_velocityX = -m_velocityX; } if (m_y < 0) { // if we're at top m_y = 1; m_velocityY = -m_velocityY; } else if (m_y > m_bottomBound) { // if we're at bottom m_y = m_bottomBound - 20; m_velocityY = -m_velocityY; } } thanks a lot for any correction and help. jibby

    Read the article

  • android progressBar problem

    - by kostas
    hi.i have a button that on click is loading rss feed.i want to load a progress bar until my list opens.i have created a progressbar,it works,but as i press the return button to return to the main menu the progress bar appears again and it doesnt stop(and not even let me see my menu).this is my code ProgressBar myProgressBar; int myProgress = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main1); Button nea = (Button) findViewById(R.id.nea); nea.setOnClickListener(new View.OnClickListener() { public void onClick (View view) { setContentView(R.layout.bar); myProgressBar=(ProgressBar)findViewById(R.id.bar); new Thread(myThread).start(); Intent myIntent = new Intent(view.getContext(), nea.class); startActivityForResult(myIntent, 0); } }); } and then,out of the onCreate private Runnable myThread = new Runnable(){ @Override public void run() { // TODO Auto-generated method stub while (myProgress<100){ try{ myHandle.sendMessage(myHandle.obtainMessage()); Thread.sleep(1000); } catch(Throwable t){ } } } Handler myHandle = new Handler(){ public void handleMessage(Message msg) { // TODO Auto-generated method stub myProgress++; myProgressBar.setProgress(myProgress); } }; };

    Read the article

  • Releasing Autopool crashes on iOS 4.0 (and only on 4.0)

    - by samsam
    Hi there. I'm wondering what could cause this. I have several methods in my code that i call using performSelectorInBackground. Within each of these methods i have an Autoreleasepool that is being alloced/initialized at the beginning and released at the end of the method. this perfectly works on iOS 3.1.3 / 3.2 / 4.2 / 4.2.1 but it fataly crashes on iOS 4.0 with a EXC_BAD_ACCESS Exception that happens after calling [myPool release]. After I noticed this strange behaviour I was thinking about rewriting portions of my code and to make my app "less parallel" in case that the client os is 4.0. After I did that, the next point where the app crashed was within the ReachabilityCallback-Method from Apples Reachability "Framework". well, now I'm not quite sure what to do. The things i do within my threaded methods is pretty simple xml parsing (no cocoa calls or stuff that would affect the UI). After each method finishes it posts a notification which the coordinating-thread listens to and once all the parallelized methods have finished, the coordinating thread calls viewcontrollers etc... I have absolutely no clue what could cause this weird behaviour. Especially because Apples Code fails as well. any help is greatly appreciated! thanks, sam

    Read the article

  • c# wpf command pattern

    - by evan
    I have a wpf gui which displays a list of information in separate window and in a separate thread from the main application. As the user performs actions in the main window the side window is updated. (For example if you clicked page down in the main window a listbox in the side window would page down). Right now the architecture for this application feels very messy and I'm sure there is a cleaner way to do it. It looks like this: Main Window contains a singleton SideWindowControl which communicates with an instance of the SideWindowDisplay using events - so, for example, the pagedown button would work like: 1) the event handler of the button on the main window calls SideWindowControl.PageDown() 2) in the PageDown() function a event is created and thrown. 3) finally the gui, ShowSideWindowDisplay is subscribing to the SideWindowControl.Actions event handles the event and actually scrolls the listbox down - note because it is in a different thread it has to do that by running the command via Dispatcher.Invoke() This just seems like a very messy way to this and there must be a clearer way (The only part that can't change is that the main window and the side window must be on different threads). Perhaps using WPF commands? I'd really appreciate any suggestions!! Thanks

    Read the article

  • tcp/ip accept not returning, but client does

    - by paquetp
    server: vxworks 6.3 calls the usual socket, bind, listen, then: for (;;) { client = accept(sfd,NULL,NULL); // pass client to worker thread } client: .NET 2.0 TcpClient constructor to connect to server that takes the string hostname and int port, like: TcpClient client = new TcpClient(server_ip, port); This is working fine when the server is compiled and executed in windows (native c++). intermittently, the constructor to TcpClient will return the instance, without throwing any exception, but the accept call in vxWorks does not return with the client fd. tcpstatShow indicates no accept occurred. What could possibly make the TcpClient constructor (which calls 'Connect') return the instance, while the accept call on the server not return? It seems to be related to what the system is doing in the background - it seems more likely to get this symptom to occur when the server is busy persisting data to flash or an NFS share when the client attempts to connect, but can happen when it isn't also. I've tried adjusting priority of the thread running accept I've looked at the size of the queue in 'listen'. There's enough. The total number of file descriptors available should be enough (haven't validated this yet though, first thing in the morning)

    Read the article

  • Are we in demand?

    - by dotnetdev
    I was made redundant in the end of November. This wasn't because I lacked required skills (although I'm a youngster and in career levels a junior dev - though I knew a lot more than was called for in my job). Anyway, I was laid off due to the whole recession/credit crunch thing going on. I worked for a small company and money got tight and I had to go. I haven't made a thread about this but I have seen threads about others being laid off and experiencing a similar fate. This leads me to the question: What is the job market like for developers? Are we in demand? I ask this question on a global level, but I live in London UK (in case anyone comes across this thread from the same area). I am a .NET dev but my secondary skillset is Flex (actionscript too) and Java, which my personal portfolio is made with. I hope to be strong enough in this to do this commercially, with a few more months of practise. Then I will have more jobs applicable to me. Unfortunately, I use agencies and sites like Jobserve/Monster.com but no new jobs are ever posted on there so when you apply to all the relevant jobs, then what? Whatsmore, a lot of companies are putting a freeze on recruitment. Thanks

    Read the article

  • Wait between tasks with SingleThreadExecutor

    - by Lord.Quackstar
    I am trying to (simply) make a blocking thread queue, where when a task is submitted the method waits until its finished executing. The hard part though is the wait. Here's my 12:30 AM code that I think is overkill: public void sendMsg(final BotMessage msg) { try { Future task; synchronized(msgQueue) { task = msgQueue.submit(new Runnable() { public void run() { sendRawLine("PRIVMSG " + msg.channel + " :" + msg.message); } }); //Add a seperate wait so next runnable doesn't get executed yet but //above one unblocks msgQueue.submit(new Runnable() { public void run() { try { Thread.sleep(Controller.msgWait); } catch (InterruptedException e) { log.error("Wait to send message interupted", e); } } }); } //Block until done task.get(); } catch (ExecutionException e) { log.error("Couldn't schedule send message to be executed", e); } catch (InterruptedException e) { log.error("Wait to send message interupted", e); } } As you can see, there's alot of extra code there just to make it wait 1.7 seconds between tasks. Is there an easier and cleaner solution out there or is this it?

    Read the article

  • How expensive is a context switch? Is it better to implement a manual task switch than to rely on OS

    - by Vilx-
    The title says it all. Imagine I have two (three, four, whatever) tasks that have to run in parallel. Now, the easy way to do this would be to create separate threads and forget about it. But on a plain old single-core CPU that would mean a lot of context switching - and we all know that context switching is big, bad, slow, and generally simply Evil. It should be avoided, right? On that note, if I'm writing the software from ground up anyway, I could go the extra mile and implement my own task-switching. Split each task in parts, save the state inbetween, and then switch among them within a single thread. Or, if I detect that there are multiple CPU cores, I could just give each task to a separate thread and all would be well. The second solution does have the advantage of adapting to the number of available CPU cores, but will the manual task-switch really be faster than the one in the OS core? Especially if I'm trying to make the whole thing generic with a TaskManager and an ITask, etc?

    Read the article

  • Domain validates but won't save

    - by marko
    I have the following setup. Class, say, Car that has a CarPart (belongsTo=[car:Car]). When I'm creating a Car I also want to create som default CarParts, so I do def car = new Car(bla bla bla) def part = new CarPart(car:car) Now, when I do car.validate() or part.validate() it seems fine. But when I do if(car.save && part.save() I get this exception: 2012-03-24 14:02:21,943 [http-8080-4] ERROR util.JDBCExceptionReporter - Batch entry 0 insert into car_part (version, car_id, id) values ('0', '297', '298') was aborted. Call getNextException to see the cause. 2012-03-24 14:02:21,943 [http-8080-4] ERROR util.JDBCExceptionReporter - ERROR: value too long for type character varying(6) 2012-03-24 14:02:21,943 [http-8080-4] ERROR events.PatchedDefaultFlushEventListener - Could not synchronize database state with session org.hibernate.exception.DataException: Could not execute JDBC batch update Stacktrace follows: java.sql.BatchUpdateException: Batch entry 0 insert into car_part (version, deal_id, id) values ('0', '297', '298') was aborted. Call getNextException to see the cause. at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2621) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1837) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:407) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2754) at $Proxy20.flush(Unknown Source) at ristretto.DealController$_closure5.doCall(DealController.groovy:109) at ristretto.DealController$_closure5.doCall(DealController.groovy) at java.lang.Thread.run(Thread.java:722) Any ideas?

    Read the article

  • Why I can't get all UDP packets?

    - by Jack
    My program use UdpClient to try to receive 27 responses from 27 hosts. The size of the response is 10KB. My broadband incoming bandwidth is 150KB/s. The 27 responses are sent from the hosts almost at the same time and for every 10 secs. However, I can only receive 8 - 17 responses each time. The number of responses that I can receive is quite dynamic but within the range. Can anyone tell me why? why can't I receive all? I understand UDP is not reliable. but I tried receiving 5 - 10 responses at the same time, it worked. I guess the network links are not so bad. The code is very simple. ON the 27 hosts, I just use UdpClient to send 10KB to my machine. On my machine, I have one UdpClient receive datagrams. Each time I get a data, I create a thread to handle it (basically handling it means just print out "I received 10KB", but it runs in a thread). listener = new UDPListener(Port); listener.Start(); while (true) { try { UDPContext context = listener.Accept(); ThreadPool.QueueUserWorkItem(new WaitCallback(HandleMessage), context); } catch (Exception) { } } If I reduce the size of the response down to 3KB, the case gets much better that roughly 25 responses can be received. Any more idea? UDP buffer problems???

    Read the article

  • AudioRecord - empty buffer

    - by Arxas
    I' m trying to record some audio using AudioRecord class. Here is my code: int audioSource = AudioSource.MIC; int sampleRateInHz = 44100; int channelConfig = AudioFormat.CHANNEL_IN_MONO; int audioFormat = AudioFormat.ENCODING_PCM_16BIT; int bufferSizeInShorts = 44100; int bufferSizeInBytes = 2*bufferSizeInShorts; short Data[] = new short[bufferSizeInShorts]; Thread recordingThread; AudioRecord audioRecorder = new AudioRecord(audioSource, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } public void startRecording(View arg0) { audioRecorder.startRecording(); recordingThread = new Thread(new Runnable() { public void run() { while (Data[bufferSizeInShorts-1] == 0) audioRecorder.read(Data, 0, bufferSizeInShorts); } }); audioRecorder.stop(); } Unfortunately my short array is empty after the recording is over. May I kindly ask you to help me figure out what's wrong?

    Read the article

  • Where are possible locations of queueing/buffering delays in Linux multicast?

    - by Matt
    We make heavy use of multicasting messaging across many Linux servers on a LAN. We are seeing a lot of delays. We basically send an enormous number of small packages. We are more concerned with latency than throughput. The machines are all modern, multi-core (at least four, generally eight, 16 if you count hyperthreading) machines, always with a load of 2.0 or less, usually with a load less than 1.0. The networking hardware is also under 50% capacity. The delays we see look like queueing delays: the packets will quickly start increasing in latency, until it looks like they jam up, then return back to normal. The messaging structure is basically this: in the "sending thread", pull messages from a queue, add a timestamp (using gettimeofday()), then call send(). The receiving program receives the message, timestamps the receive time, and pushes it in a queue. In a separate thread, the queue is processed, analyzing the difference between sending and receiving timestamps. (Note that our internal queues are not part of the problem, since the timestamps are added outside of our internal queuing.) We don't really know where to start looking for an answer to this problem. We're not familiar with Linux internals. Our suspicion is that the kernel is queuing or buffering the packets, either on the send side or the receive side (or both). But we don't know how to track this down and trace it. For what it's worth, we're using CentOS 4.x (RHEL kernel 2.6.9).

    Read the article

  • C# threading solution for long queries

    - by Eddie
    Senerio We have an application that records incidents. An external database needs to be queried when an incident is approved by a supervisor. The queries to this external database are sometimes taking a while to run. This lag is experienced through the browser. Possible Solution I want to use threading to eliminate the simulated hang to the browser. I have used the Thread class before and heard about ThreadPool. But, I just found BackgroundWorker in this post. MSDN states: The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution. Is BackgroundWorker the way to go when handling long running queries? What happens when 2 or more BackgroundWorker processes are ran simultaneously? Is it handled like a pool?

    Read the article

< Previous Page | 159 160 161 162 163 164 165 166 167 168 169 170  | Next Page >