Search Results

Search found 4335 results on 174 pages for 'wait'.

Page 37/174 | < Previous Page | 33 34 35 36 37 38 39 40 41 42 43 44  | Next Page >

  • Java: Implement own message queue (threadsafe)

    - by derMax
    The task is to implement my own messagequeue that is thread safe. My approach: public class MessageQueue { /** * Number of strings (messages) that can be stored in the queue. */ private int capacity; /** * The queue itself, all incoming messages are stored in here. */ private Vector<String> queue = new Vector<String>(capacity); /** * Constructor, initializes the queue. * * @param capacity The number of messages allowed in the queue. */ public MessageQueue(int capacity) { this.capacity = capacity; } /** * Adds a new message to the queue. If the queue is full, it waits until a message is released. * * @param message */ public synchronized void send(String message) { //TODO check } /** * Receives a new message and removes it from the queue. * * @return */ public synchronized String receive() { //TODO check return "0"; } } If the queue is empty and I call remove(), I want to call wait() so that another thread can use the send() method. Respectively, I have to call notifyAll() after every iteration. Question: Is that possible? I mean does it work that when I say wait() in one method of an object, that I can then execute another method of the same object? And another question: Does that seem to be clever?

    Read the article

  • twython search api rate limit: Header information will not be updated

    - by user2715478
    I want to handle the Search-API rate limit of 180 requests / 15 minutes. The first solution I came up with was to check the remaining requests in the header and wait 900 seconds. See the following snippet: results = search_interface.cursor(search_interface.search, q=k, lang=lang, result_type=result_mode) while True: try: tweet = next(results) if limit_reached(search_interface): sleep(900) self.writer(tweet) def limit_reached(search_interface): remaining_rate = int(search_interface.get_lastfunction_header('X-Rate-Limit-Remaining')) return remaining_rate <= 2 But it seems, that the header information are not reseted to 180 after it reached the two remaining requests. The second solution I came up with was to handle the twython exception for rate limitation and wait the remaining amount of time: results = search_interface.cursor(search_interface.search, q=k, lang=lang, result_type=result_mode) while True: try: tweet = next(results) self.writer(tweet) except TwythonError as inst: logger.error(inst.msg) wait_for_reset(search_interface) continue except StopIteration: break def wait_for_reset(search_interface): reset_timestamp = int(search_interface.get_lastfunction_header('X-Rate-Limit-Reset')) now_timestamp = datetime.now().timestamp() seconds_offset = 10 t = reset_timestamp - now_timestamp + seconds_offset logger.info('Waiting {0} seconds for Twitter rate limit reset.'.format(t)) sleep(t) But with this solution I receive this message INFO: Resetting dropped connection: api.twitter.com" and the loop will not continue with the last element of the generator. Have somebody faced the same problems? Regards.

    Read the article

  • Testing Async downloads with ASIHTTPRequest

    - by Baishampayan Ghose
    I am writing a simple library using ASIHTTPRequest where I am fetching URLs in an async manner. My problem is that the main function that I have written to test my lib exits before the async calls are finished. I am very new to Obj C and iPhone development, can anyone suggest a good way to wait before all the requests are finished in the main function? Currently, my main function looks like this - int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; IBGApp *ibgapp = [[IBGApp alloc] init]; IBGLib *ibgl = [[IBGLib alloc] initWithUsername:@"joe" andPassword:@"xxx"]; // The two method calls below download URLs async. [ibgl downloadURL:@"http://yahoo.com/" withRequestDelegate:ibgapp andRequestSelector:@selector(logData:)]; [ibgl downloadURL:@"http://google.com/" withRequestDelegate:ibgapp andRequestSelector:@selector(logData:)]; [pool release]; return 0; // I reach here before the async calls are done. } So what is the best way to wait till the async calls are done? I tried putting sleep, but obviously doesn't work.

    Read the article

  • JMF microphone volume controller

    - by TacB0sS
    How to obtain the Microphone volume controller in JMF? this is what I have: I tried this implementation concept of yours, but I keep getting a null from the first volume processor when I try to get the stream, here is how I do it: // the device is the media device specifically audio Processor processorForVolume = Manager.createProcessor(device.getLocator()); // wait until configured ProcessorStates newState = new ProcessorStateListener(Processor.Configured).waitForProcessorState(processorForVolume); System.out.println("volumeProcessorState: "+newState); // setting the content descriptor to null - read in another thread this allows to get the gain control processorForVolume.setContentDescriptor(null); // set the track control format to one supported by the device and the track control. // I didn't match it to an RTP allowed format, but I don't think this has anything to do with it... TrackControl[] trackControls = processorForVolume.getTrackControls(); if (trackControls.length == 0) throw new MC_Exception("No track controls where found for this device:", new Object[]{device}); for (TrackControl control : trackControls) trackManipulator.manipulateTrackControls(control); // wait until the processor is realized newState = new ProcessorStateListener(Controller.Realized).waitForProcessorState(processorForVolume); System.out.println("volumeProcessorState: "+newState); // receives the gain control micVolumeController = processorForVolume.getGainControl(); // cannot get the output stream to process further... any suggestions? processor = Manager.createProcessor(processorForVolume.getDataOutput()); new ProcessorStateListener(Processor.Configured).waitForProcessorState(processor); processor.setContentDescriptor(DeviceCapturingManager.RAW_RTP); new ProcessorStateListener(Controller.Realized).waitForProcessorState(processor); this is the output It generates: volumeProcessorState: Configured format set to track control - com.sun.media.ProcessEngine$ProcTControl@1627c16: LINEAR, 48000.0 Hz, 16-bit, Stereo, LittleEndian, Signed volumeProcessorState: Realized and the data output from the processor is Null. I should make clear that when the content descriptor != null I do get an output stream but not the volume controller, and the when it is null I get the controller, but no stream. I try to connect to an audio microphone device Adam.

    Read the article

  • Optimizing a shared buffer in a producer/consumer multithreaded environment

    - by Etan
    I have some project where I have a single producer thread which writes events into a buffer, and an additional single consumer thread which takes events from the buffer. My goal is to optimize this thing for a single machine to achieve maximum throughput. Currently, I am using some simple lock-free ring buffer (lock-free is possible since I have only one consumer and one producer thread and therefore the pointers are only updated by a single thread). #define BUF_SIZE 32768 struct buf_t { volatile int writepos; volatile void * buffer[BUF_SIZE]; volatile int readpos;) }; void produce (buf_t *b, void * e) { int next = (b->writepos+1) % BUF_SIZE; while (b->readpos == next); // queue is full. wait b->buffer[b->writepos] = e; b->writepos = next; } void * consume (buf_t *b) { while (b->readpos == b->writepos); // nothing to consume. wait int next = (b->readpos+1) % BUF_SIZE; void * res = b->buffer[b->readpos]; b->readpos = next; return res; } buf_t *alloc () { buf_t *b = (buf_t *)malloc(sizeof(buf_t)); b->writepos = 0; b->readpos = 0; return b; } However, this implementation is not yet fast enough and should be optimized further. I've tried with different BUF_SIZE values and got some speed-up. Additionaly, I've moved writepos before the buffer and readpos after the buffer to ensure that both variables are on different cache lines which resulted also in some speed. What I need is a speedup of about 400 %. Do you have any ideas how I could achieve this using things like padding etc?

    Read the article

  • Drag and Drop in Silverlight with F# and Asynchronous Workflows

    - by knotig
    Hello everyone! I'm trying to implement drag and drop in Silverlight using F# and asynchronous workflows. I'm simply trying to drag around a rectangle on the canvas, using two loops for the the two states (waiting and dragging), an idea I got from Tomas Petricek's book "Real-world Functional Programming", but I ran into a problem: Unlike WPF or WinForms, Silverlight's MouseEventArgs do not carry information about the button state, so I can't return from the drag-loop by checking if the left mouse button is no longer pressed. I only managed to solve this by introducing a mutable flag. Would anyone have a solution for this, that does not involve mutable state? Here's the relevant code part (please excuse the sloppy dragging code, which snaps the rectangle to the mouse pointer): type MainPage() as this = inherit UserControl() do Application.LoadComponent(this, new System.Uri("/SilverlightApplication1;component/Page.xaml", System.UriKind.Relative)) let layoutRoot : Canvas = downcast this.FindName("LayoutRoot") let rectangle1 : Rectangle = downcast this.FindName("Rectangle1") let mutable isDragged = false do rectangle1.MouseLeftButtonUp.Add(fun _ -> isDragged <- false) let rec drag() = async { let! args = layoutRoot.MouseMove |> Async.AwaitEvent if (isDragged) then Canvas.SetLeft(rectangle1, args.GetPosition(layoutRoot).X) Canvas.SetTop(rectangle1, args.GetPosition(layoutRoot).Y) return! drag() else return() } let wait() = async { while true do let! args = Async.AwaitEvent rectangle1.MouseLeftButtonDown isDragged <- true do! drag() } Async.StartImmediate(wait()) () Thank you very much for your time!

    Read the article

  • problem with fork()

    - by john
    I'm writing a shell which forks, with the parent reading the input and the child process parsing and executing it with execvp. pseudocode of main method: do{ pid = fork(); print pid; if (p<0) { error; exit; } if (p>0) { wait for child to finish; read input; } else { call function to parse input; exit; } }while condition return; what happens is that i never seem to enter the child process (pid printed is always positive, i never enter the else). however, if i don't call the parse function and just have else exit, i do correctly enter parent and child alternatingly. full code: int main(int argc, char *argv[]){ char input[500]; pid_t p; int firstrun = 1; do{ p = fork(); printf("PID: %d", p); if (p < 0) {printf("Error forking"); exit(-1);} if (p > 0){ wait(NULL); firstrun = 0; printf("\n> "); bzero(input, 500); fflush(stdout); read(0, input, 499); input[strlen(input)-1] = '\0'; } else exit(0); else { if (parse(input) != 0 && firstrun != 1) { printf("Error parsing"); exit(-1); } exit(0); } }while(strcmp(input, "exit") != 0); return 0; }

    Read the article

  • c# calling process "cannot find the file specified"

    - by laura
    I'm a c# newbie so bear with me. I'm trying to call "pslist" from PsTools from a c# app, but I keep getting "The system cannot find the file specified". I thought I read somewhere on google that the exe should be in c:\windows\system32, so I tried that, still nothing. Even trying the full path to c:\windows\system32\PsList.exe is not working. I can open other things like notepad or regedit. Any ideas? C:\WINDOWS\system32dir C:\WINDOWS\SYSTEM32\PsList.exe Volume in drive C has no label. Volume Serial Number is ECC0-70AA Directory of C:\WINDOWS\SYSTEM32 04/27/2010 11:04 AM 231,288 PsList.exe 1 File(s) 231,288 bytes 0 Dir(s) 8,425,492,480 bytes free try { // Start the child process. Process p = new Process(); // Redirect the output stream of the child process. p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; //This works //p.StartInfo.FileName = @"C:\WINDOWS\regedit.EXE"; //This doesn't p.StartInfo.FileName = @"C:\WINDOWS\system32\PsList.exe"; p.Start(); // Do not wait for the child process to exit before // reading to the end of its redirected stream. p.WaitForExit(); // Read the output stream first and then wait. s1 = p.StandardOutput.ReadToEnd(); p.WaitForExit(); } catch (Exception ex) { Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString()); Console.ReadLine(); }

    Read the article

  • Sending and receiving IM messages via controller in Rails

    - by Grnbeagle
    Hi, I need a way to handle XMPP communication in my Rails app. My requirements are: Keep an instance of XMPP client running and logged in as one specific user (my bot user) Trigger an event from a controller to send a message and wait for a reply. The message is sent to another machine equipped with a bot so that the reply is supposed to be returned quickly. I installed xmpp4r and backgrounDrb similar to what's described here, but backgrounDrb seems to have evolved and I couldn't get it to wait for a reply. If it has to happen asynchronously, I am willing to use a server-push technology to notify the browser when the reply arrives. To give you a better idea, here are snippets of my code: (In controller) class ServicesController < ApplicationController layout 'simple' def index render :text => "index" end def show @my_service = Service.find(params[:id]) worker = MiddleMan.worker(:jabber_agent_worker) worker.send_request(:arg => {:jid => "someuser@someserver", :cmd => "help"}) render :text => "testing" end end (In worker script) require 'xmpp4r' require 'logger' class JabberAgentWorker < BackgrounDRb::MetaWorker set_worker_name :jabber_agent_worker def create(args = nil) jid = Jabber::JID.new('myagent@myserver') @client = Jabber::Client.new(jid) @client.connect @client.auth('pass') @client.send(Jabber::Presence.new.set_show(:chat).set_status('BackgrounDRb')) @client.add_message_callback do |message| logger.info("**** messaged received: #{message}") # never reaches here end end def send_request(args = nil) to_jid = Jabber::JID.new(args[:jid]) message = Jabber::Message::new(to_jid, args[:cmd]).set_type(:normal).set_id('1') @client.send(message) end end If anyone can tell me any of the following, I'd much appreciate it: issue with my backgrounDrb usage other background process alternatives appropriate for XMPP interactions other ways of achieving this Thanks in advance.

    Read the article

  • Cannot access Class methods from previous windows form - C#

    - by George
    I am writing an app, still, where I need to test some devices every minute for 30 minutes. It made sense to use a timer set to kick off every 60 secs and do whats required in the event handler. However, I need the app to wait for the 30 mins until I have finished with the timer since the following code alters the state of the devices I am trying to monitor. I obviously don't want to use any form of loop to do this. I thought of using another windows form, since I also display the progress, which will simply kick off the timer and wait until its complete. The problem I am having with this is that I use a device Class and cant seem to get access to the methods in the device class from the 2nd (3rd actually - see below) windows form. I have an initial windows form where I get input from the user, then call the 2nd windows form where it work out which tests need to be done and which device classes need to be used, and then I want to call the 3rd windows form to handle the timer. I will have up to 6-7 device classes and so wanted to only instantiate them when actually requiring them, from the 2nd form. Should I have put this logic into the 1st windows form (program class ??) ? Would I not still have the problem of not being able to access device class methods from there too ? Anyway, perhaps someone knows of a better way to do the checks every minute without the rest of the code executing (and changing the status of the devices) or how I should be accessing the methods in the app ?? Well that's the problem, I cant get that part of it to work correctly. Here is the definition for the calling form including the device class - namespace NdtStart { public partial class fclsNDTCalib : Form { NDTClass NDT = new NDTClass(); public fclsNDTCalib() (new fclsNDTTicker(NDT)).ShowDialog(); Here is the class def for the called form - namespace NdtStart { public partial class fclsNDTTicker : Form { public fclsNDTTicker() I tried lots but couldn't get the arguments to work.

    Read the article

  • Threads in Java

    - by owca
    I've created simple program to test Threads in Java. I'd like it to print me numbers infinitely, like 123123123123123. Dunno why, but currently it stops after one cycle finishing 213 only. Anyone knows why ? public class Main { int number; public Main(int number){ } public static void main(String[] args) { new Infinite(2).start(); new Infinite(1).start(); new Infinite(3).start(); } } class Infinite extends Thread { static int which=1; static int order=1; int id; int number; Object console = new Object(); public Infinite(int number){ id = which; which++; this.number = number; } @Override public void run(){ while(1==1){ synchronized(console){ if(order == id){ System.out.print(number); order++; if(order >= which){ order = 1; } try{ console.notifyAll(); console.wait(); } catch(Exception e) {} } else { try{ console.notifyAll(); console.wait(); } catch(Exception e) {} } } try{Thread.sleep(0);} catch(Exception e) {} } } }

    Read the article

  • How can I work out what events are being waited for with WinDBG in a kernel debug session

    - by Benj
    I'm a complete WinDbg newbie and I've been trying to debug a WindowsXP problem that a customer has sent me where our software and some third party software prevent windows from logging off. I've reproduced the problem and have verified that only when our software and the customers software are both installed (although not necessarily running at logoff) does the log off problem occur. I've observed that WM_ENDSESSION messages are not reaching the running windows when the user tries to log off and I know that the third party software uses a kernel driver. I've been looking at the processes in WinDbg and I know that csrss.exe would normally send all the windows a WM_ENDSESSION message. When I ran: !process 82356020 6 To look at csrss.exe's stack I can see: WARNING: Frame IP not in any known module. Following frames may be wrong. 00000000 00000000 00000000 00000000 00000000 0x7c90e514 THREAD 8246d998 Cid 0248.02a0 Teb: 7ffd7000 Win32Thread: e1627008 WAIT: (WrUserRequest) UserMode Non-Alertable 8243d9f0 SynchronizationEvent 81fe0390 SynchronizationEvent Not impersonating DeviceMap e1004450 Owning Process 82356020 Image: csrss.exe Attached Process N/A Image: N/A Wait Start TickCount 1813 Ticks: 20748 (0:00:05:24.187) Context Switch Count 3 LargeStack UserTime 00:00:00.000 KernelTime 00:00:00.000 Start Address 0x75b67cdf Stack Init f80bd000 Current f80bc9c8 Base f80bd000 Limit f80ba000 Call 0 Priority 14 BasePriority 13 PriorityDecrement 0 DecrementCount 0 Kernel stack not resident. ChildEBP RetAddr Args to Child f80bc9e0 80500ce6 00000000 8246d998 804f9af2 nt!KiSwapContext+0x2e (FPO: [Uses EBP] [0,0,4]) f80bc9ec 804f9af2 804f986e e1627008 00000000 nt!KiSwapThread+0x46 (FPO: [0,0,0]) f80bca24 bf80a4a3 00000002 82475218 00000001 nt!KeWaitForMultipleObjects+0x284 (FPO: [Non-Fpo]) f80bca5c bf88c0a6 00000001 82475218 00000000 win32k!xxxMsgWaitForMultipleObjects+0xb0 (FPO: [Non-Fpo]) f80bcd30 bf87507d bf9ac0a0 00000001 f80bcd54 win32k!xxxDesktopThread+0x339 (FPO: [Non-Fpo]) f80bcd40 bf8010fd bf9ac0a0 f80bcd64 00bcfff4 win32k!xxxCreateSystemThreads+0x6a (FPO: [Non-Fpo]) f80bcd54 8053d648 00000000 00000022 00000000 win32k!NtUserCallOneParam+0x23 (FPO: [Non-Fpo]) f80bcd54 7c90e514 00000000 00000022 00000000 nt!KiFastCallEntry+0xf8 (FPO: [0,0] TrapFrame @ f80bcd64) This waitForMultipleObjects looks interesting because I'm wondering if csrss.exe is waiting on some event which isn't arriving to allow the logoff. Can anyone tell me how I might find out what event it's waiting for anything else I might do to further investigate the problem?

    Read the article

  • SQLite transaction doesn't work as expected

    - by troll
    I prepared 2 files, "1.php" and "2.php". "1.php" is like this. <?php $dbh = new PDO('sqlite:test1'); $dbh->beginTransaction(); print "aaa<br>"; sleep(55); $dbh->commit(); print "bbb"; ?> and "2.php" is like this. <?php $dbh = new PDO('sqlite:test1'); $dbh->beginTransaction(); print "ccc<br>"; $dbh->commit(); print "ddd"; ?> and I excute "1.php". It starts a transaction and waits 55 seconds. So when I immediately excute "2.php", my expectation is this: "1.php" is getting transaction and "1" holds a database lock "2" can not begin a transaction "2" can not get database lock so "2" have to wait 55 seconds BUT, but the test went another way. When I excute "2",then "2" immediately returned it's result "2" did not wait so I have to think that "1" could not get transaction, or could not get database lock. Can anyone help?

    Read the article

  • python can't start a new thread

    - by Giorgos Komnino
    I am building a multi threading application. I have setup a threadPool. [ A Queue of size N and N Workers that get data from the queue] When all tasks are done I use tasks.join() where tasks is the queue . The application seems to run smoothly until suddently at some point (after 20 minutes in example) it terminates with the error thread.error: can't start new thread Any ideas? Edit: The threads are daemon Threads and the code is like: while True: t0 = time.time() keyword_statuses = DBSession.query(KeywordStatus).filter(KeywordStatus.status==0).options(joinedload(KeywordStatus.keyword)).with_lockmode("update").limit(100) if keyword_statuses.count() == 0: DBSession.commit() break for kw_status in keyword_statuses: kw_status.status = 1 DBSession.commit() t0 = time.time() w = SWorker(threads_no=32, network_server='http://192.168.1.242:8180/', keywords=keyword_statuses, cities=cities, saver=MySqlRawSave(DBSession), loglevel='debug') w.work() print 'finished' When the daemon threads are killed? When the application finishes or when the work() finishes? Look at the thread pool and the worker (it's from a recipe ) from Queue import Queue from threading import Thread, Event, current_thread import time event = Event() class Worker(Thread): """Thread executing tasks from a given tasks queue""" def __init__(self, tasks): Thread.__init__(self) self.tasks = tasks self.daemon = True self.start() def run(self): '''Start processing tasks from the queue''' while True: event.wait() #time.sleep(0.1) try: func, args, callback = self.tasks.get() except Exception, e: print str(e) return else: if callback is None: func(args) else: callback(func(args)) self.tasks.task_done() class ThreadPool: """Pool of threads consuming tasks from a queue""" def __init__(self, num_threads): self.tasks = Queue(num_threads) for _ in range(num_threads): Worker(self.tasks) def add_task(self, func, args=None, callback=None): ''''Add a task to the queue''' self.tasks.put((func, args, callback)) def wait_completion(self): '''Wait for completion of all the tasks in the queue''' self.tasks.join() def broadcast_block_event(self): '''blocks running threads''' event.clear() def broadcast_unblock_event(self): '''unblocks running threads''' event.set() def get_event(self): '''returns the event object''' return event

    Read the article

  • Blackberry Keyboard Lock timeout

    - by Vernon
    I want this blackberry 9700 to "fully lock" as soon as I click the icon for the "Keyboard Lock" application. Currently I have to wait 5 to 7 seconds for the screen to go dark after each time I click the "Keyboard Lock" icon. During that time if something touches the touch pad, then the 5-7 second timer resets and you have to wait another 5 to 7 seconds for the screen to go dark and "fully lock" After it finally goes dark, touching the touch pad does not reset the timer. At that point it is "fully locked" and requires a key to be pressed. How can I get it to "fully lock" as soon as the lock icon is clicked? I want the screen to go dark immediately, and for it to require a key press to request an unlock. I have tried Options - Screen/Keyboard - Backlight Timeout ... etc ... none of that reduces the timeout for the "Keyboard Lock" application. And there does not seem to be an option screen for the "Keyboard Lock" application, that I can find. NOTE: This is occurring with BlackBerry 9700 v5.0.0.330 (Platform 5.1.0.91)

    Read the article

  • BackgroundWorker and foreach loop

    - by tomfox66
    I have to process a loop with backgroundworkers. Before I start a new loop iteration I need to wait until the provious backgroundworker has finished. A while loop inside my foreach loop with isbusy flag doesn's seem like a good idea to me. How should I design this loop so it waits for the bg-worker to end before iterating the loop public void AutoConnect() { string[] HardwareList = new string[] { "d1", "d4", "ds1_2", "ds4_2" }; foreach (string HW in HardwareList) { if (backgroundWorker1.IsBusy != true) { backgroundWorker1.RunWorkerAsync(HW); // Wait here until backgroundWorker1 finished } } } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; string FileName = e.Argument as string; try { if ((worker.CancellationPending == true)) { e.Cancel = true; } else { // Time consuming operation ParseFile(Filename); } } catch { } } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { label1.Text = e.ProgressPercentage.ToString() + " lines"; } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if(e.Cancelled == true) { //this.tbProgress.Text = "Canceled!"; } else if(!(e.Error == null)) { //this.tbProgress.Text = ("Error: " + e.Error.Message); } else { label1.text = "Done!"; } }

    Read the article

  • The CLR has been unable to transition from COM context [...] for 60 seconds

    - by BlueRaja The Green Unicorn
    I am getting this error on code that used to work. I have not changed the code. Here is the full error: The CLR has been unable to transition from COM context 0x3322d98 to COM context 0x3322f08 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations. And here is the code that caused it: var openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); openFileDialog1.DefaultExt = "mdb"; openFileDialog1.Filter = "Management Database (manage.mdb)|manage.mdb"; //Stalls indefinitely on the following line, then gives the CLR error //one minute later. The dialog never opens. if(openFileDialog1.ShowDialog() == DialogResult.OK) { .... } Yes, I am sure the dialog is not open in the background, and no, I don't have any explicit COM code or unmanaged marshalling or multithreading. I have no idea why the OpenFileDialog won't open - any ideas?

    Read the article

  • Pump Messages During Long Operations + C# (it is urgent)

    - by Newbie
    Hi I have a web service that is doing huge computation and is taking more than a minute. I have generated the proxy file of the web service and then from my client end I am using the dll(of course I generated the proxy dll). My client side code is TimeSeries3D t = new TimeSeries3D(); int portfolioId = 4387919; string[] str = new string[2]; str[0] = "MKT_CAP"; DateRange dr = new DateRange(); dr.mStartDate = DateTime.Today; dr.mEndDate = DateTime.Today; Service1 sc = new Service1(); t = sc.GetAttributesForPortfolio(portfolioId, true, str, dr); But since it is taking to much time for the server to compute, after 1 minute I am receiving an error message The CLR has been unable to transition from COM context 0x33caf30 to COM context 0x33cb0a0 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations. Kindly guide me what to do? It is very urgent. Thanks

    Read the article

  • Runing bcdedit from python in Windows 2008 SP2

    - by Lee-Man
    I do not know windows well, so that may explain my dilemma ... I am trying to run bcdedit in Windows 2008R2 from Python 2.6. My Python routine to run a command looks like this: def run_program(cmd_str): """Run the specified command, returning its output as an array of lines""" dprint("run_program(%s): entering" % cmd_str) cmd_args = cmd_str.split() subproc = subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (outf, errf) = (subproc.stdout, subproc.stderr) olines = outf.readlines() elines = errf.readlines() if Options.debug: if elines: dprint('Error output:') for line in elines: dprint(line.rstrip()) if olines: dprint('Normal output:') for line in olines: dprint(line.rstrip()) errf.close() outf.close() res = subproc.wait() dprint('wait result=', res) return (res, olines) I call this function thusly: (res, o) = run_program('bcdedit /set {current} MSI forcedisable') This command works when I type it from a cmd window, and it works when I put it in a batch file and run it from a command window (as Administrator, of course). But when I run it from Python (as Administrator), Python claims it can't find the command, returning: bcdedit is not recognized as an internal or external command, operable program or batch file Also, if I trying running my batch file from Python (which works from the command line), it also fails. I've also tried it with the full path to bcdedit, with the same results. What is it about calling bcdedit from Python that makes it not found? Note that I can call other EXE files from Python, so I have some level of confidence that my Python code is sane ... but who knows. Any help would be most appreciated.

    Read the article

  • Creating A Single Threaded Server with AnyEvent (Perl)

    - by David Williams
    I'm working on creating a local service to listen on localhost and provide a basic call and response type interface. What I'd like to start with is a baby server that you can connect to over telnet and echoes what it receives. I've heard AnyEvent is great for this, but the documentation for AnyEvent::Socket does not give a very good example how to do this. I'd like to build this with AnyEvent, AnyEvent::Socket and AnyEvent::Handle. Right now the little server code looks like this: #!/usr/bin/env perl use AnyEvent; use AnyEvent::Handle; use AnyEvent::Socket; my $cv = AnyEvent->condvar; my $host = '127.0.0.1'; my $port = 44244; tcp_server($host, $port, sub { my($fh) = @_; my $cv = AnyEvent->condvar; my $handle; $handle = AnyEvent::Handle->new( fh => $fh, poll => "r", on_read => sub { my($self) = @_; print "Received: " . $self->rbuf . "\n"; $cv->send; } ); $cv->recv; }); print "Listening on $host\n"; $cv->wait; This doesn't work and also if I telnet to localhost:44244 I get this: EV: error in callback (ignoring): AnyEvent::CondVar: recursive blocking wait attempted at server.pl line 29. I think if I understand how to make a mini, single threaded server that simply prints out whatever its given and then waits for more input, I could take it a lot further from there. Any ideas?

    Read the article

  • MUD (game) design concept question about timed events.

    - by mudder
    I'm trying my hand at building a MUD (multiplayer interactive-fiction game) I'm in the design/conceptualizing phase and I've run into a problem that I can't come up with a solution for. I'm hoping some more experienced programmers will have some advice. Here's the problem as best I can explain it. When the player decides to perform an action he sends a command to the server. the server then processes the command, determines whether or not the action can be performed, and either does it or responds with a reason as to why it could not be done. One reason that an action might fail is that the player is busy doing something else. For instance, if a player is mid-fight and has just swung a massive broadsword, it might take 3 seconds before he can repeat this action. If the player attempts to swing again to soon, the game will respond indicating that he must wait x seconds before doing that. Now, this I can probably design without much trouble. The problem I'm having is how I can replicate this behavior from AI creatures. All of the events that are being performed by the server ON ITS OWN, aka not as an immediate reaction to something a player has done, will have to be time sensitive. Some evil monster has cast a spell on you but must wait 30 seconds before doing it again... I think I'll probably be adding all these events to some kind of event queue, but how can I make that event queue time sensitive?

    Read the article

  • asyncore callbacks launching threads... ok to do?

    - by sbartell
    I'm unfamiliar with asyncore, and have very limited knowledge of asynchronous programming except for a few intro to twisted tutorials. I am most familiar with threads and use them in all my apps. One particular app uses a couchdb database as its interface. This involves longpolling the db looking for changes and updates. The module I use for couchdb is couchdbkit. It uses an asyncore loop to watch for these changes and send them to a callback. So, I figure from this callback is where I launch my worker threads. It seems a bit crude to mix asynchronous and threaded programming. I really like couchdbkit, but would rather not introduce issues into my program. So, my question is, is it safe to fire threads from an async callback? Here's some code... {{{ def dispatch(change): global jobs, db_url # jobs is my queue db = Database(db_url) work_order = db.get(change['id']) # change is an id to the document that changed. # i need to get the actual document (workorder) worker = Worker(work_order, db) # fire the thread jobs.append[worker] worker.start() return main() . . . consumer.wait(cb=dispatch, since=update_seq, timeout=10000) #wait constains the asyncloop. }}}

    Read the article

  • How to interrupt a thread performing a blocking socket connect?

    - by Jason R
    I have some code that spawns a pthread that attempts to maintain a socket connection to a remote host. If the connection is ever lost, it attempts to reconnect using a blocking connect() call on its socket. Since the code runs in a separate thread, I don't really care about the fact that it uses the synchronous socket API. That is, until it comes time for my application to exit. I would like to perform some semblance of an orderly shutdown, so I use thread synchronization primitives to wake up the thread and signal for it to exit, then perform a pthread_join() on the thread to wait for it to complete. This works great, unless the thread is in the middle of a connect() call when I command the shutdown. In that case, I have to wait for the connect to time out, which could be a long time. This makes the application appear to take a long time to shut down. What I would like to do is to interrupt the call to connect() in some way. After the call returns, the thread will notice my exit signal and shut down cleanly. Since connect() is a system call, I thought that I might be able to intentionally interrupt it using a signal (thus making the call return EINTR), but I'm not sure if this is a robust method in a POSIX threads environment. Does anyone have any recommendations on how to do this, either using signals or via some other method? As a note, the connect() call is down in some library code that I cannot modify, so changing to a non-blocking socket is not an option.

    Read the article

  • Why do InterruptedExceptions clear a thread's interrupted status?

    - by Hanno Fietz
    If a thread is interrupted while inside Object.wait() or Thread.join(), it throws an InterruptedException, which resets the thread's interrupted status. I. e., if I have a loop like this inside a Runnable.run(): while (!this._workerThread.isInterrupted()) { // do something try { synchronized (this) { this.wait(this._waitPeriod); } } catch (InterruptedException e) { if (!this._isStopping()) { this._handleFault(e); } } } the thread will continue to run after calling interrupt(). This means I have to explicitly break out of the loop by checking for my own stop flag in the loop condition, rethrow the exception, or add a break. Now, this is not exactly a problem, since this behaviour is well documented and doesn't prevent me from doing anything the way I want. However, I don't seem to understand the concept behind it: Why is a thread not considered interrupted anymore once the exception has been thrown? A similar behaviour also occurs if you get the interrupted status with interrupted() instead of isInterrupted(), then, too, the thread will only appear interrupted once. Am I doing something unusual here? For example, is it more common to catch the InterruptedException outside the loop? (Even though I'm not exactly a beginner, I tagged this "beginner", because it seems like a very basic question to me, looking at it.)

    Read the article

  • Pump Messages During Long Operations + C#

    - by Newbie
    Hi I have a web service that is doing huge computation and is taking more than a minute. I have generated the proxy file of the web service and then from my client end I am using the dll(of course I generated the proxy dll). My client side code is TimeSeries3D t = new TimeSeries3D(); int portfolioId = 4387919; string[] str = new string[2]; str[0] = "MKT_CAP"; DateRange dr = new DateRange(); dr.mStartDate = DateTime.Today; dr.mEndDate = DateTime.Today; Service1 sc = new Service1(); t = sc.GetAttributesForPortfolio(portfolioId, true, str, dr); But since it is taking to much time for the server to compute, after 1 minute I am receiving an error message The CLR has been unable to transition from COM context 0x33caf30 to COM context 0x33cb0a0 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations. Kindly guide me what to do? Thanks

    Read the article

< Previous Page | 33 34 35 36 37 38 39 40 41 42 43 44  | Next Page >