Search Results

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

Page 51/344 | < Previous Page | 47 48 49 50 51 52 53 54 55 56 57 58  | Next Page >

  • Is this a correct Interlocked synchronization design?

    - by Dan Bryant
    I have a system that takes Samples. I have multiple client threads in the application that are interested in these Samples, but the actual process of taking a Sample can only occur in one context. It's fast enough that it's okay for it to block the calling process until Sampling is done, but slow enough that I don't want multiple threads piling up requests. I came up with this design (stripped down to minimal details): public class Sample { private static Sample _lastSample; private static int _isSampling; public static Sample TakeSample(AutomationManager automation) { //Only start sampling if not already sampling in some other context if (Interlocked.CompareExchange(ref _isSampling, 0, 1) == 0) { try { Sample sample = new Sample(); sample.PerformSampling(automation); _lastSample = sample; } finally { //We're done sampling _isSampling = 0; } } return _lastSample; } private void PerformSampling(AutomationManager automation) { //Lots of stuff going on that shouldn't be run in more than one context at the same time } } Is this safe for use in the scenario I described?

    Read the article

  • java and threads: very strange behaviour

    - by Derk
    private synchronized Map<Team, StandingRow> calculateStanding() { System.out.println("Calculate standing for group " + getName()); Map<Team, StandingRow> standing = new LinkedHashMap<Team, StandingRow>(); for (Team team : teams) { standing.put(team, new StandingRow(team)); } StandingRow homeTeamRow, awayTeamRow; for (Match match : matches.values()) { homeTeamRow = standing.get(match.getHomeTeam()); awayTeamRow = standing.get(match.getAwayTeam()); System.out.println("Contains key for " + match.getHomeTeam() + ": " + standing.containsKey(match.getHomeTeam())); System.out.println("Contains key for " + match.getAwayTeam() + ": " + standing.containsKey(match.getAwayTeam())); } } This is my code. matches contains 6 elements, but the problem is that after two matches no keys are anymore found in the standing map. The output is for example Contains key for Zuid-Afrika: true Contains key for Mexico: true Contains key for Uruguay: true Contains key for Frankrijk: true Contains key for Zuid-Afrika: false Contains key for Uruguay: false Contains key for Frankrijk: false Contains key for Mexico: false Contains key for Mexico: false Contains key for Uruguay: false Contains key for Frankrijk: false Contains key for Zuid-Afrika: false This is in a threaded environment, but the method is synchronized so I thought that this would not give a problem? I have also a simple unit test for this method and that works well.

    Read the article

  • Queuing methods to be run on an object by different threads in Python

    - by Ben
    Let's say I have an object who's class definition looks like: class Command: foo = 5 def run(self, bar): time.sleep(1) self.foo = bar return self.foo If this class is instantiated once, but different threads are hitting its run method (via an HTTP request, handled separately) passing in different args, what is the best method to queue them? Can this be done in the class definition itself?

    Read the article

  • Decoding a jpg in the background in WP7

    - by Shahar Prish
    I have a bunch of apps in the marketplace, and so far I have been able, by changing my functionality or going the extra mile, to work around the issue of being unable to decode a jpg in the background into a WriteableBitmap. I am finding a situation where I can't think of good ways to "work around" the issue. I need to decode the image I get from MediaLibrary, reduce it's resolution to something managable (800x800), rotate it potentially and save to local storage. By far, the thing that takes the most time (80%) is decoding the bitmap to 800x800 - it takes between 700ms to 1000 ms. A user may add 7-10 images when starting, which translates to ~10 seconds of waiting for the images being added. I tried doing this lazily, but at some point you need to pay the piper and the app essentially stutters for ~1000ms at that point and the experience is not great. Is there an alternative I am missing for loading the image in the background somehow? (Note on why CreateOptions.BackgroundCreation is no good for me: It loads the image into a BitmapImage which is great if you want to just use it, but not so great for what I need to do which is create a copy in Isolated Storage).

    Read the article

  • Cross Theaded Calls - Many controls Heavy GUI Application after .net 1.1 2.0 upgrade- best way ??

    - by keepsmilinyaar
    I have recently upgraded a .net1.1 solution to .net2.0. AS this is a very heavy GUI appilcation with loads of controls and many multithreaded operations that update the GUI. While these operations worked seamlessly in .net1.1 it is throwing up Cross Threaded Illegal operations after the upgrade. Considering the fact that tehre are numerous grids, buttons and status labels that need to be updated via these multi threaded operations, I decided to code for checking the InvokeRequired solution, however doing that for every control would probably not be the best way to go about it. I was wondering if you could suggest a better way of how I can go about it or propose any OOPS based class structure that I could code around to make the code look better. Please do let me know if my question is unclear. Thanks in advance

    Read the article

  • SQLite bulk insert on iPhone not working

    - by App_beginner
    Hi. I have been struggling with this seeminly easy problem for 48 hours, and I am no closer to a solution. So I was hoping that someone might be able to help me. I am building a app, that use a combination of a local (SQLite) database and an online database (PHP/MYSQL). The app is nearly finished. Checked for leaks and work like a charm. However the very last part is the part I have struggled with. On launch, I want the app to check for changes to the online databse, and if there is. I want it to download and parse a xml file containing the changes. Everything is working fine this far. But when I try to bulk insert my parsed data to my database, the app crashes, giving a NSInternalInconsistency error. Due to the database returning SQLITE_MISUSE. I have done a lot of googling, but am still unable to solve my problem. So I am putting the code here, hoping that someone can help me fix this. And I know that I should have used core data for this. But this is the very last part I am struggling with, and I am very reluctant to changing my entire code now. Core data will have to come in the update. Here is the error I recieve: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error while inserting data. 'library routine called out of sequence'' Here is my code: -(void)UpdateDatabase:(const char *)_query NewValues:(NSMutableArray *)_odb dbn:(NSString *)_dbn dbp:(NSString *)_dbp { sqlite3 *database; NSMutableArray *NewValues = _odb; int i; const char *query = _query; sqlite3_stmt *addStmt; for (i = 1; i < [NewValues count]; i++) { if(sqlite3_prepare_v2(database, query, -1, &addStmt, NULL) == SQLITE_OK) { sqlite3_bind_text(addStmt, 1, [[[NewValues objectAtIndex:i] name] UTF8String], -1, SQLITE_TRANSIENT); sqlite3_bind_text(addStmt, 2, [[[NewValues objectAtIndex:i] city]UTF8String], -1, SQLITE_TRANSIENT); sqlite3_bind_double(addStmt, 3, [[[NewValues objectAtIndex:i] lat] doubleValue]); sqlite3_bind_int(addStmt, 4, [[[NewValues objectAtIndex:i] long] doubleValue]); sqlite3_bind_int(addStmt, 5, [[[NewValues objectAtIndex:i] code] intValue]); } if(SQLITE_DONE != sqlite3_step(addStmt)) { NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database)); } //Reset the add statement. sqlite3_reset(addStmt); } }

    Read the article

  • Is this a valid pattern for raising events in C#?

    - by Will Vousden
    Update: For the benefit of anyone reading this, since .NET 4, the lock is unnecessary due to changes in synchronization of auto-generated events, so I just use this now: public static void Raise<T>(this EventHandler<T> handler, object sender, T e) where T : EventArgs { if (handler != null) { handlerCopy(sender, e); } } And to raise it: SomeEvent.Raise(this, new FooEventArgs()); Having been reading one of Jon Skeet's articles on multithreading, I've tried to encapsulate the approach he advocates to raising an event in an extension method like so (with a similar generic version): public static void Raise(this EventHandler handler, object @lock, object sender, EventArgs e) { EventHandler handlerCopy; lock (@lock) { handlerCopy = handler; } if (handlerCopy != null) { handlerCopy(sender, e); } } This can then be called like so: protected virtual void OnSomeEvent(EventArgs e) { this.someEvent.Raise(this.eventLock, this, e); } Are there any problems with doing this? Also, I'm a little confused about the necessity of the lock in the first place. As I understand it, the delegate is copied in the example in the article to avoid the possibility of it changing (and becoming null) between the null check and the delegate call. However, I was under the impression that access/assignment of this kind is atomic, so why is the lock necessary? Update: With regards to Mark Simpson's comment below, I threw together a test: static class Program { private static Action foo; private static Action bar; private static Action test; static void Main(string[] args) { foo = () => Console.WriteLine("Foo"); bar = () => Console.WriteLine("Bar"); test += foo; test += bar; test.Test(); Console.ReadKey(true); } public static void Test(this Action action) { action(); test -= foo; Console.WriteLine(); action(); } } This outputs: Foo Bar Foo Bar This illustrates that the delegate parameter to the method (action) does not mirror the argument that was passed into it (test), which is kind of expected, I guess. My question is will this affect the validity of the lock in the context of my Raise extension method? Update: Here is the code I'm now using. It's not quite as elegant as I'd have liked, but it seems to work: public static void Raise<T>(this object sender, ref EventHandler<T> handler, object eventLock, T e) where T : EventArgs { EventHandler<T> copy; lock (eventLock) { copy = handler; } if (copy != null) { copy(sender, e); } }

    Read the article

  • What image processing Library should I use

    - by Swippen
    I have been reading What is the best image manipulation library? And tried a few libraries and are now looking for inputs on what is the best for our need. I will start by describing our current setting and problems. We have a system that needs to resize and crop a large amount of images from big original images. We handle 50 000+ images every day on 2 powerfull servers. Today we use ImageGlue from WebSupergoo but we don't like it at all, it is slow and hangs the service now and then (Its in another unanswered stack overflow question). We have a threaded windows service that uses Microsoft ThreadPool to resize as much as possible on the 8 core machines. I have tried AForge and it went very well it was loads faster and never crashed or anything. But I had problems with quality on a few images. This due to what algorithms I used ofc so can be tweaked. But want to widen our eyes to see if thats the right way to go. so: It needs to be c# .net and run in a windows service. (Since we wont change the rest of the service only image handling) It needs to handle threaded environment well. We have a great need of it being fast since today its too slow. But we also want good quality and small filesize since the images are later displayed on webpage with loads of visitors and needs good quality. So we have a lot of demands on ability to get god quality at a fast pace, and also secondary keep filesizes lowered even if that can be adjusted with compression a bit. Any comments or suggestions on what library to use?

    Read the article

  • Are indivisible operations still indivisible on multiprocessor and multicore systems?

    - by Steve314
    As per the title, plus what are the limitations and gotchas. For example, on x86 processors, alignment for most data types is optional - an optimisation rather than a requirement. That means that a pointer may be stored at an unaligned address, which in turn means that pointer might be split over a cache page boundary. Obviously this could be done if you work hard enough on any processor (picking out particular bytes etc), but not in a way where you'd still expect the write operation to be indivisible. I seriously doubt that a multicore processor can ensure that other cores can guarantee a consistent all-before or all-after view of a written pointer in this unaligned-write-crossing-a-page-boundary situation. Am I right? And are there any similar gotchas I haven't thought of?

    Read the article

  • Returning values from Swing using invokeAndWait

    - by Joonas Pulakka
    I've been using the following approach to create components and return values from Swing to/from outside the EDT. For instance, the following method could be an extension to JFrame, to create a JPanel and add it to the parent JFrame: public JPanel threadSafeAddPanel() { final JPanel[] jPanel = new JPanel[1]; try { EventQueue.invokeAndWait(new Runnable() { public void run() { jPanel[0] = new JPanel(); add(jPanel[0]); } }); } catch (InterruptedException ex) { } catch (InvocationTargetException ex) { } return jPanel[0]; } The local 1-length array is used to transfer the "result" from inside the Runnable, which is invoked in the EDT. Well, it looks "a bit" hacky, and so my questions: Does this make sense? Is anybody else doing something like this? Is the 1-length array a good way of transferring the result? Is there an easier way to do this?

    Read the article

  • What is wrong with locking non-static fields? What is the correct way to lock a particular instance?

    - by smartcaveman
    Why is it considered bad practice to lock non-static fields? And, if I am not locking non-static fields, then how do I lock an instance method without locking the method on all other instances of the same or derived class? I wrote an example to make my question more clear. public abstract class BaseClass { private readonly object NonStaticLockObject = new object(); private static readonly object StaticLockObject = new object(); protected void DoThreadSafeAction<T>(Action<T> action) where T: BaseClass { var derived = this as T; if(derived == null) { throw new Exception(); } lock(NonStaticLockObject) { action(derived); } } } public class DerivedClass :BaseClass { private readonly Queue<object> _queue; public void Enqueue(object obj) { DoThreadSafeAction<DerivedClass>(x=>x._queue.Enqueue(obj)); } } If I make the lock on the StaticLockObject, then the DoThreadSafeAction method will be locked for all instances of all classes that derive from BaseClass and that is not what I want. I want to make sure that no other threads can call a method on a particular instance of an object while it is locked.

    Read the article

  • how do i know how many clients are calling my WCF service function

    - by ZhengZhiren
    i am writing a program to test WCF service performance in high concurrency circumstance. On client side, i start many threads to call a WCF service function which returns a long list of data object. On server side, in that function called by my client, i need to know the number of clients calling the function. For doing that, i set a counter variable. In the beginning of the function, i add the counter by 1, but how can i decrease it after the funtion has returned the result? int clientCount=0; public DataObject[] GetData() { Interlocked.Increment(ref clientCount); List<DataObject> result = MockDb.GetData(); return result.ToArray(); Interlocked.Decrement(ref clientCount); //can't run to here... } i have seen a way in c++. Create a new class named counter. In the constructor of the counter class, increase the variable. And decrease it in the destructor. In the function, make a counter object so that its constructor will be called. And after the function returns, its destructor will be called. Like this: class counter { public: counter(){++clientCount; /* not simply like this, need to be atomic*/} ~counter(){--clientCount; /* not simply like this, need to be atomic*/} }; ... myfunction() { counter c; //do something return something; } In c# i think i can do so with the following codes, but not for sure. public class Service1 : IService1 { static int clientCount = 0; private class ClientCounter : IDisposable { public ClientCounter() { Interlocked.Increment(ref clientCount); } public void Dispose() { Interlocked.Decrement(ref clientCount); } } public DataObject[] GetData() { using (ClientCounter counter = new ClientCounter()) { List<DataObject> result = MockDb.GetData(); return result.ToArray(); } } } i write a counter class implement the IDisposable interface. And put my function codes into a using block. But it seems that it doesn't work so good. No matter how many threads i start, the clientCount variable is up to 3. Any advise would be appreciated.

    Read the article

  • DOM Storage and locks

    - by user535759
    Since DOM storage and its equivalencies persist in between tabs and windows, I've thought about using it for message passing. The problem is that fetch and store are different operations, and therefore not atomic. I have models that rely on UUID generation, conflict resolutions, and beaconing to do the small subset of what I need to do, but my real question is this: Since the local storage is a shared memory resource, what are the locking mechanisms available for mutual access?

    Read the article

  • How to use Multiple Variables for a lock Scope in C#

    - by Gunner
    I have a situation where a block of code should be executed only if two locker objects are free. I was hoping there would be something like: lock(a,b) { // this scope is in critical region } However, there seems to be nothing like that. So does it mean the only way for doing this is: lock(a) { lock(b) { // this scope is in critical region } } Will this even work as expected? Although the code compiles, but I am not sure whether it would achieve what I am expecting it to.

    Read the article

  • What's a good algorithm for searching arrays N and M, in order to find elements in N that also exist

    - by GenTiradentes
    I have two arrays, N and M. they are both arbitrarily sized, though N is usually smaller than M. I want to find out what elements in N also exist in M, in the fastest way possible. To give you an example of one possible instance of the program, N is an array 12 units in size, and M is an array 1,000 units in size. I want to find which elements in N also exist in M. (There may not be any matches.) The more parallel the solution, the better. I used to use a hash map for this, but it's not quite as efficient as I'd like it to be. Typing this out, I just thought of running a binary search of M on sizeof(N) independent threads. (Using CUDA) I'll see how this works, though other suggestions are welcome.

    Read the article

  • Execute a block of database querys

    - by Nightmare
    I have the following task to complete: In my program a have a block of database querys or questions. I want to execute these questions and wait for the result of all questions or catch an error if one question fails! My Question object looks like this (simplified): public class DbQuestion(String sql) { [...] } [...] //The answer is just a holder for custom data... public void SetAnswer(DbAnswer answer) { //Store the answer in the question and fire a event to the listeners this.OnAnswered(EventArgs.Empty); } [...] public void SetError() { //Signal an Error in this query! this.OnError(EventArgs.Empty); } So every question fired to the database has a listener that waits for the parsed result. Now I want to fire some questions asynchronous to the database (max. 5 or so) and fire an event with the data from all questions or an error if only one question throws one! Which is the best or a good way to accomplish this task? Can I really execute more then one question parallel and stop all my work when one question throws an error? I think I need some inspiration on this... Just a note: I´m working with .NET framework 2.0

    Read the article

  • Java: Allowing the child thread to kill itself on InterruptedException?

    - by Zombies
    I am using a ThreadPool via ExecutorService. By calling shutDownNow() it interrupts all running threads in the pool. When this happens I want these threads to give up their resources (socket and db connections) and simply die, but without continuing to run anymore logic, eg: inserting anything into the DB. What is the simplest way to achieve this? Bellow is some sample code: public void threadTest() { Thread t = new Thread(new Runnable() { public void run() { try { Thread.sleep(999999); } catch (InterruptedException e) { //invoke thread suicide logic here } } }); t.start(); t.interrupt(); try { Thread.sleep(4000); } catch (InterruptedException e) { } }

    Read the article

  • Why isn't it possible to update an ObservableCollection from a different thread?

    - by MainMa
    In a multi-threaded WPF application, it is not possible to update an ObservableCollection from a thread other than WPF window thread. I know there are workarounds, so my question is not how to avoid the "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread" exception. My question is, why there is such an exception? Why wasn't it possible to allow collection updates from any thread? Personally, I don't see any reason to block UI update when ObservableCollection is changed from other threads. If two threads (including parallel ones) are accessing the same object, one listening for changes of object properties through events, the other one doing changes, it will always work, at least if locks are used properly. So, what are the reasons?

    Read the article

  • How is executed a SendMessage from a different thread?

    - by Lorenzo
    When we send a message, "if the specified window was created by the calling thread, the window procedure is called immediately as a subroutine". But "if the specified window was created by a different thread, the system switches to that thread and calls the appropriate window procedure. Messages sent between threads are processed only when the receiving thread executes message retrieval code." (taken from MSDN documentation for SendMessage). Now, I don't understand how (or, more appropriately, when) the target windows procedure is called. Of course the target thread will not be preempted (the program counter is not changed). I presume that the call will happen during some wait function (like GetMessage or PeekMessage), it is true? That process is documented in detail somewhere?

    Read the article

  • Do really need a count lock on Multi threads with one CPU core?

    - by MrROY
    If i have some code looks like this(Please ignore the syntax, i want to understand it without a specified language): count = 0 def countDown(): count += 1 if __name__ == '__main__': thread1(countDown) thread2(countDown) thread3(countDown) Here i have a CPU with only one core, do i really need a lock to the variable count in case of it could be over-written by other threads. I don't know, but if the language cares a lot, please explain it under Java?C and Python, So many thanks.

    Read the article

< Previous Page | 47 48 49 50 51 52 53 54 55 56 57 58  | Next Page >