Search Results

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

Page 82/344 | < Previous Page | 78 79 80 81 82 83 84 85 86 87 88 89  | Next Page >

  • .NET: Control Invoke() in Reflector

    - by sheepsimulator
    So, I was getting back into some .NET programming, and through a new feature in VS.NET 2010, it detected a case where I was trying to modify a control from a thread that didn't create that control, and pointed me to an article on MSDN about how you do this correctly... ' HOW TO WRITE TO A FORM CONTROL FROM A THREAD THAT DIDN'T CREATE THE CONTROL ' =========================================================================== ' Say you need to write to a UI text box that logs stuff... Delegate Sub WriteLogDelegate(ByVal [text] As String) Private Sub WriteLog(ByVal [text] As String) If Me.rtfLog.InvokeRequired Then ' We are not in the same thread! ' Create new WriteLogDelegate and invoke it on the same thread Dim d As New WriteLogDelegate(AddressOf WriteLog) Me.rtfLog.Invoke(d, New Object() {[text]}) Else ' We are totally in the same thread... ' Call AppendText like normal! Me.rtfLog.AppendText([text]) End If End Sub AND I WAS SO EXCITED BECAUSE I HAVE BEEN PUZZLED BY HOW TO DO THIS FOR LIKE 5 YEARS BECAUSE PREVIOUS VERSIONS OF VS.NET DIDN'T FLAG THIS SINCE I WAS AN UNDERGRAD ON A PROJECT AND... Umm... Sorry bout that. Composure regained. Anyway, now that I know this bit of .NET-fu, I'd like to learn more about what's going on and how it works. Where can I find the code for Invoke() in .NET Reflector?

    Read the article

  • Creating a blocking Queue<T> in .NET?

    - by spoon16
    I have a scenario where I have multiple threads adding to a queue and multiple threads reading from the same queue. If the queue reaches a specific size all threads that are filling the queue will be blocked on add until an item is removed from the queue. The solution below is what I am using right now and my question is: How can this be improved? Is there an object that already enables this behavior in the BCL that I should be using? internal class BlockingCollection<T> : CollectionBase, IEnumerable { //todo: might be worth changing this into a proper QUEUE private AutoResetEvent _FullEvent = new AutoResetEvent(false); internal T this[int i] { get { return (T) List[i]; } } private int _MaxSize; internal int MaxSize { get { return _MaxSize; } set { _MaxSize = value; checkSize(); } } internal BlockingCollection(int maxSize) { MaxSize = maxSize; } internal void Add(T item) { Trace.WriteLine(string.Format("BlockingCollection add waiting: {0}", Thread.CurrentThread.ManagedThreadId)); _FullEvent.WaitOne(); List.Add(item); Trace.WriteLine(string.Format("BlockingCollection item added: {0}", Thread.CurrentThread.ManagedThreadId)); checkSize(); } internal void Remove(T item) { lock (List) { List.Remove(item); } Trace.WriteLine(string.Format("BlockingCollection item removed: {0}", Thread.CurrentThread.ManagedThreadId)); } protected override void OnRemoveComplete(int index, object value) { checkSize(); base.OnRemoveComplete(index, value); } internal new IEnumerator GetEnumerator() { return List.GetEnumerator(); } private void checkSize() { if (Count < MaxSize) { Trace.WriteLine(string.Format("BlockingCollection FullEvent set: {0}", Thread.CurrentThread.ManagedThreadId)); _FullEvent.Set(); } else { Trace.WriteLine(string.Format("BlockingCollection FullEvent reset: {0}", Thread.CurrentThread.ManagedThreadId)); _FullEvent.Reset(); } } }

    Read the article

  • uh-oh windows mobile threading issues!

    - by violet313
    specifically WM6x, winCE5x Now my current understanding from trawling the msdn etal is that the IMAPIAdviseSink::OnNotify callback can be made from any old thread; from (ce)mapi or perhaps even from a third-party service provider. Under WM6x, i cannot seem to coax an in-thread response by invoking HrThisThreadAdviseSink, since while this function is declared in mapiutil.h, a definition appears not to exist (in cemapi.lib or wherever??) ~But i notice that all the OnNotify callbacks i get, derive from windows messages that i am receiving on my thread (=looks to me like an in-thread implementation in any case under cemapi)... So, can anyone confirm that this is infact always the case -or am i just getting lucky right now? ah, i should add that my advise source is IMAPISession::Advise (ActiveSync) erm i should also say that i might have cross-posted this on the msdn forum -but they're mostly numptys over there,,

    Read the article

  • Multi-Threading Question Concerning WPF

    - by Andrew
    Hello, I'm a newbie to threading, and I don't really know how to code a particular task. I would like to handle a mouse click event on a window that will kick off a while loop in a seperate thread. This thread, which is distinct from the UI thread, should call a function in the while loop which updates a label on the window being serviced by the UI thread. The while loop should stop running when the left mouse button is no longer being pressed. All the loop does is increment a counter, and then repeatedly call the function which displays the updated value in the window. The code for the window and all of the threading is given below (I keep getting some error about STA threading, but don't know where to put the attribute). Also, I'm hoping to use this solution, if it ever works, in another project that makes asynchronous calls elsewhere to a service via wcf, so I was hoping not to make any application-wide special configurations, since I'm really new to multi-threading and am quite worried about breaking other code in a larger program... Here's what I have: <Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication2" Name="MyMainWindow" Title="MainWindow" Width="200" Height="150" PreviewMouseLeftButtonDown="MyMainWindow_PreviewMouseLeftButtonDown"> <Label Height="28" Name="CounterLbl" /> </Window> And here's the code-behind: using System.Windows; using System.Windows.Input; using System.Threading; namespace WpfApplication2 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private int counter = 0; public MainWindow() { InitializeComponent(); } private delegate void EmptyDelegate(); private void MyMainWindow_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Thread counterThread = new Thread(new ThreadStart(MyThread)); counterThread.Start(); } private void MyThread() { while (Mouse.LeftButton == MouseButtonState.Pressed) { counter++; Dispatcher.Invoke(new EmptyDelegate(UpdateLabelContents), null); } } private void UpdateLabelContents() { CounterLbl.Content = counter.ToString(); } } } Anyways, multi-threading is really new to me, and I don't have any experience implementing it, so any thoughts or suggestions are welcome! Thanks, Andrew

    Read the article

  • My multithread program works slowly or appear deadlock on dual core machine, please help

    - by Shangping Guo
    I have a program with several threads, one thread will change a global when it exits itself and the other thread will repeatedly poll the global. No any protection on the globals. The program works fine on uni-processor. On dual core machine, it works for a while and then halt either on Sleep(0) or SuspendThread(). Would anyone be able to help me out on this? The code would be like this: Thread 1: do something... while(1) { ..... flag_thread1_running=false; SuspendThread(GetCurrentThread()); continue; } Thread 2 .... while(flag_thread1_running==false) Sleep(0); ....

    Read the article

  • What is a good method to use with multithreading to simulate this?

    - by user1504257
    I am writing a program in c++ in visual studio to be able to handle a line at a park. I have all of my customers in a line at the park and I want to be able to service them using multithreading with openmp. When I put the pragma and such in, I have multiple threads servicing the same customer at the same time for each and every customer I create, not what I want. I want for example, if I had two threads and four customers, that thread one to do customer one while thread 2 does customer 2. Then I would like thread 1 to do customer 3 and thread 2 customer 4 at the same time. I don't know if its possible or if there is a better way, but I need to use openmp. Thanks for your input.

    Read the article

  • rails Rake and mysql ssh port forwarding.

    - by rube_noob
    Hello, I need to create a rake task to do some active record operations via a ssh tunnel. The rake task is run on a remote windows machine so I would like to keep things in ruby. This is my latest attempt. desc "Syncronizes the tablets DB with the Server" task(:sync => :environment) do require 'rubygems' require 'net/ssh' begin Thread.abort_on_exception = true tunnel_thread = Thread.new do Thread.current[:ready] = false hostname = 'host' username = 'tunneluser' Net::SSH.start(hostname, username) do|ssh| ssh.forward.local(3333, "mysqlhost.com", 3306) Thread.current[:ready] = true puts "ready thread" ssh.loop(0) { true } end end until tunnel_thread[:ready] == true do end puts "tunnel ready" Importer.sync rescue StandardError => e puts "The Database Sync Failed." end end The task seems to hang at "tunnel ready" and never attempts the sync. I have had success when running first a rake task to create the tunnel and then running the rake sync in a different terminal. I want to combine these however so that if there is an error with the tunnel it will not attempt the sync. This is my first time using ruby Threads and Net::SSH forwarding so I am not sure what is the issue here. Any Ideas!? Thanks

    Read the article

  • Producer and Consumer Threads Hang

    - by user972425
    So this is my first foray into threads and thus far it is driving me insane. My problem seems to be some kind of synchronization error that causes my consumer thread to hang. I've looked at other code and just about everything I could find and I can't find what my error is. There also seems to be a discrepancy between the code being executed in Eclipse and via javac in the command line. Intention - Using a bounded buffer (with 1000 slots) create and consume 1,000,000 doubles. Use only notify and wait. Problem - In Eclipse the consumer thread will occasionally hang around 940,000 iterations, but other times completes. In the command line the consumer thread always hangs. Output - Eclipse - Successful Producer has produced 100000 doubles. Consumer has consumed 100000 doubles. Producer has produced 200000 doubles. Consumer has consumed 200000 doubles. Producer has produced 300000 doubles. Consumer has consumed 300000 doubles. Producer has produced 400000 doubles. Consumer has consumed 400000 doubles. Producer has produced 500000 doubles. Consumer has consumed 500000 doubles. Producer has produced 600000 doubles. Consumer has consumed 600000 doubles. Producer has produced 700000 doubles. Consumer has consumed 700000 doubles. Producer has produced 800000 doubles. Consumer has consumed 800000 doubles. Producer has produced 900000 doubles. Consumer has consumed 900000 doubles. Producer has produced 1000000 doubles. Producer has produced all items. Consumer has consumed 1000000 doubles. Consumer has consumed all items. Exitting Output - Command Line/Eclipse - Unsuccessful Producer has produced 100000 doubles. Consumer has consumed 100000 doubles. Producer has produced 200000 doubles. Consumer has consumed 200000 doubles. Producer has produced 300000 doubles. Consumer has consumed 300000 doubles. Producer has produced 400000 doubles. Consumer has consumed 400000 doubles. Producer has produced 500000 doubles. Consumer has consumed 500000 doubles. Producer has produced 600000 doubles. Consumer has consumed 600000 doubles. Producer has produced 700000 doubles. Consumer has consumed 700000 doubles. Producer has produced 800000 doubles. Consumer has consumed 800000 doubles. Producer has produced 900000 doubles. Consumer has consumed 900000 doubles. Producer has produced 1000000 doubles. Producer has produced all items. At this point it just sits and hangs. Any help you can provide about where I might have misstepped is greatly appreciated. Code - Producer thread import java.text.DecimalFormat;+ " doubles. Cumulative value of generated items= " + temp) import java.util.*; import java.io.*; public class producer implements Runnable{ private buffer produceBuff; public producer (buffer buff){ produceBuff = buff; } public void run(){ Random random = new Random(); double temp = 0, randomElem; DecimalFormat df = new DecimalFormat("#.###"); for(int i = 1; i<=1000000; i++) { randomElem = (Double.parseDouble( df.format(random.nextDouble() * 100.0))); try { produceBuff.add(randomElem); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } temp+= randomElem; if(i%100000 == 0) {produceBuff.print("Producer has produced "+ i ); } } produceBuff.print("Producer has produced all items."); } } Consumer thread import java.util.*; import java.io.*; public class consumer implements Runnable{ private buffer consumBuff; public consumer (buffer buff){ consumBuff = buff; } public void run(){ double temp = 0; for(int i = 1; i<=1000000; i++) { try { temp += consumBuff.get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(i%100000 == 0) {consumBuff.print("Consumer has consumed "+ i ); //if(i>999000) //{System.out.println("Consuming item " + i);} } consumBuff.print("Consumer has consumed all items."); } } Buffer/Main import java.util.*; import java.io.*; public class buffer { private double buff[]; private int addPlace; private int getPlace; public buffer(){ buff = new double[1000]; addPlace = 0; getPlace = 0; } public synchronized void add(double add) throws InterruptedException{ if((addPlace+1 == getPlace) ) { try { wait(); } catch (InterruptedException e) {throw e;} } buff[addPlace] = add; addPlace = (addPlace+1)%1000; notify(); } public synchronized double get()throws InterruptedException{ if(getPlace == addPlace) { try { wait(); } catch (InterruptedException e) {throw e;} } double temp = buff[getPlace]; getPlace = (getPlace+1)%1000; notify(); return temp; } public synchronized void print(String view) { System.out.println(view); } public static void main(String args[]){ buffer buf = new buffer(); Thread produce = new Thread(new producer(buf)); Thread consume = new Thread(new consumer(buf)); produce.start(); consume.start(); try { produce.join(); consume.join(); } catch (InterruptedException e) {return;} System.out.println("Exitting"); } }

    Read the article

  • Is ReaderWriterLockSlim.EnterUpgradeableReadLock() essentially the same as Monitor.Enter()?

    - by Neil Barnwell
    So I have a situation where I may have many, many reads and only the occasional write to a resource shared between multiple threads. A long time ago I read about ReaderWriterLock, and have read about ReaderWriterGate which attempts to mitigate the issue where many writes coming in trump reads and hurt performance. However, now I've become aware of ReaderWriterLockSlim... From the docs, I believe that there can only be one thread in "upgradeable mode" at any one time. In a situation where the only access I'm using is EnterUpgradeableReadLock() (which is appropriate for my scenario) then is there much difference to just sticking with lock(){}? Here's the excerpt: A thread that tries to enter upgradeable mode blocks if there is already a thread in upgradeable mode, if there are threads waiting to enter write mode, or if there is a single thread in write mode. Or, does the recursion policy make any difference to this?

    Read the article

  • serial port does not exist in current context: c#

    - by I__
    here's the code: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public class ThreadWork { private static SerialPort serialPort1; public static void DoWork() { serialPort1.Open(); serialPort1.Write("AT+CMGF=1\r\n"); //Thread.Sleep(500); serialPort1.Write("AT+CNMI=2,2\r\n"); //Thread.Sleep(500); serialPort1.Write("AT+CSCA=\"+4790002100\"\r\n"); //Thread.Sleep(500); serialPort1.DataReceived += serialPort1_DataReceived_1; } } private void Form1_Load(object sender, EventArgs e) { ThreadStart myThreadDelegate = new ThreadStart(ThreadWork.DoWork); Thread myThread = new Thread(myThreadDelegate); myThread.Start(); } private void serialPort1_DataReceived_1(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { string response = serialPort1.ReadLine(); this.BeginInvoke(new MethodInvoker(() => textBox1.AppendText(response + "\r\n"))); } } } and i get an error on this line: string response = serialPort1.ReadLine(); it says:: Error 1 The name 'serialPort1' does not exist in the current context C:\Users\alexluvsdanielle\AppData\Local\Temporary Projects\WindowsFormsApplication1\Form1.cs 44 31 WindowsFormsApplication1 what am i doing wrong?

    Read the article

  • redefineClasses in JVMTI

    I have two questions Does redefineClasses work with JIT enabled JVM? If so, in multithreaded applications, if one thread uses redefineClasses to redefine a class, does another thread see that redefined class? (especially, if the other thread is running jit compiled code?)

    Read the article

  • How to detect that the internet connection has got disconnected through a java desktop application?

    - by Yatendra Goel
    I am developing a Java Desktop Application that access internet. It is a multi-threaded application, each thread do the same work (means each thread is an instance of same Thread class). Now, as all the threads need internet connection to be active, there should be some mechanism that detects whether an internet connection is active or not. Q1. How to detect whether the internet connection is active or not? Q2. Where to implement this internet-status-check-mechanism code? Should I start a separate thread for checking internet status regularly and notifies all the threads when the status changes from one state to another? Or should I let each thread check for the internet-status itself? Q3. This issue should be a very common issue as every application accessing an internet should deal with this problem. So how other developers usually deal with this problem? Q4. If you could give me a reference to a good demo application that addresses this issue then it would greatly help me.

    Read the article

  • .NET Windows Service, threads and garbage collection (possible memory leaks)

    - by Evgeny
    I am developing a .NET Windows service that is creating a couple of threads and then uses these threads to send print jobs to printers (there is a thread for each printer). I have some issues which sometimes can be fixed by restarting the service. Some issues also arise when the service has been running for a while. This makes me suspect a possible memory leak. So, a couple of questions: Would a garbage collector collect an object if it was created inside a thread, or will the object exist until the thread is stopped/terminated? What tools can I use to monitor the amount of memory used by a Windows service and by a thread that I am starting programmatically?

    Read the article

  • Socket Read In Multi-Threaded Application Returns Zero Bytes or EINTR (-1)

    - by user309670
    Hi. Am a c-coder for a while now - neither a newbie nor an expert. Now, I have a certain daemoned application in C on a PPC Linux. I use PHP's socket_connect as a client to connect to this service locally. The server uses epoll for concurrent connections via a Unix socket. A user submitted string is parsed for certain characters/words using strstr() and if found, spawns 4 joinable threads to different websites simultaneously. I use socket, connect, write and read, to interact with the said webservers via TCP on port 80 in each thread. All connections and writes seems successful. Reads to the webserver sockets fail however, with either (A) all 3 threads seem to hang, and only one thread returns -1 and errno is set to 104. The responding thread takes like 10 minutes - an eternity long:-(. *I read somewhere that the 104 (is EINTR) suggests that ...'the connection was reset by peer', or (B) 0 bytes from 3 threads, and only 1 of the 4 threads actually returns some data. Isn't the socket read/write thread-safe? Otherwise, use thread-safe (and reentrant) libc functions such as strtok_r, gethostbyname_r, etc. *I doubt that the said webhosts are actually resetting the connection, because when I run a single-threaded standalone (everything else equal) all things works perfectly right. There's a second problem too (oops), I can't write back to the client who connect to my epoll-ed Unix socket. My daemon application will hang and hog CPU 100% for ever. Yet nothing is written to the clients end. Am sure the client (a very typical PHP socket application) hasn't closed the connection whenever this is happening - no error(s) detected either. I cannot figure-out whatever is wrong even with Valgrind or GDB

    Read the article

  • How can I remove a JPanel from a JFrame?

    - by Roman
    Recently I asked here how to add a new JPanel to JFrame. The answer helped me to get a working code. But not I have a related question: "How can I remove an old JPanel". I need that because of the following problem. A new JPanel appears appears when I want (either time limit is exceeded or user press the "Submit" button). But in several seconds some element of the old JPanel appears together with the component of the new JPanel. I do not understand why it happens. I thought that it is because I have to other threads which update the window. But the first thread just add the old panel once (so, it should be finished). And in the second thread I have a loop which is broken (so, it also should be finished). Here is my code: private Thread controller = new Thread() { public void run() { // First we set the initial pane (for the selection of partner). SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getContentPane().add(generatePartnerSelectionPanel()); frame.invalidate(); frame.validate(); } }); // Update the pane for the selection of the parnter. for (int i=40; i>0; i=i-1) { final int sec = i; SwingUtilities.invokeLater(new Runnable() { public void run() { timeLeftLabel.setText(sec + " seconds left."); } }); try {Thread.sleep(1000);} catch (InterruptedException e) {} if (partnerSubmitted) {break;} } // For the given user the selection phase is finished (either the time is over or form was submitted). SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getContentPane().add(generateWaitForGamePanel()); frame.invalidate(); frame.validate(); } }); } };

    Read the article

  • How can two threads access a common array of buffers with minimal blocking ? (c#)

    - by Jelly Amma
    Hello, I'm working on an image processing application where I have two threads on top of my main thread: 1 - CameraThread that captures images from the webcam and writes them into a buffer 2 - ImageProcessingThread that takes the latest image from that buffer for filtering. The reason why this is multithreaded is because speed is critical and I need to have CameraThread to keep grabbing pictures and making the latest capture ready to pick up by ImageProcessingThread while it's still processing the previous image. My problem is about finding a fast and thread-safe way to access that common buffer and I've figured that, ideally, it should be a triple buffer (image[3]) so that if ImageProcessingThread is slow, then CameraThread can keep on writing on the two other images and vice versa. What sort of locking mechanism would be the most appropriate for this to be thread-safe ? I looked at the lock statement but it seems like it would make a thread block-waiting for another one to be finished and that would be against the point of triple buffering. Thanks in advance for any idea or advice. J.

    Read the article

  • Stuck in Infinite Loop while PostInvalidating

    - by Nicholas Roge
    I'm trying to test something, however, the loop I'm using keeps getting stuck while running. It's just a basic lock thread while doing something else before continuing kind of loop. I've double checked that I'm locking AND unlocking the variable I'm using, but regardless it's still stuck in the loop. Here are the segments of code I have that cause the problem: ActualGame.java: Thread thread=new Thread("Dialogue Thread"){ @Override public void run(){ Timer fireTimer=new Timer(); int arrowSequence=0; gameHandler.setOnTouchListener( new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent me) { //Do something. if(!gameHandler.fireTimer.getActive()){ exitLoop=true; } return false; } } ); while(!exitLoop){ while(fireTimer.getActive()||!gameHandler.drawn); c.drawBitmap(SpriteSheet.createSingleBitmap(getResources(), R.drawable.dialogue_box,240,48),-48,0,null); c.drawBitmap(SpriteSheet.createSingleBitmap(getResources(),R.drawable.dialogue_continuearrow,32,16,8,16,arrowSequence,0),-16,8,null); gameHandler.drawn=false; gameHandler.postInvalidate(); if(arrowSequence+1==4){ arrowSequence=0; exitLoop=true; }else{ arrowSequence++; } fireTimer.startWait(100); } gameHandler.setOnTouchListener(gameHandler.defaultOnTouchListener); } }; thread.run(); And the onDraw method of GameHandler: canvas.scale(scale,scale); canvas.translate(((screenWidth/2)-((terrainWidth*scale)/2))/scale,((screenHeight/2)-((terrainHeight*scale)/2))/scale); canvas.drawColor(Color.BLACK); for(int layer=0;layer(less than)tiles.length;layer++){ if(layer==playerLayer){ canvas.drawBitmap(playerSprite.getCurrentSprite(), playerSprite.getPixelLocationX(), playerSprite.getPixelLocationY(), null); continue; } for(int y=0;y(less than)tiles[layer].length;y++){ for(int x=0;x(less than)tiles[layer][y].length;x++){ if(layer==0&&tiles[layer][y][x]==null){ tiles[layer][y][x]=nullTile; } if(tiles[layer][y][x]!=null){ runningFromTileEvent=false; canvas.drawBitmap(tiles[layer][y][x].associatedSprite.getCurrentSprite(),x*tiles[layer][y][x].associatedSprite.spriteWidth,y*tiles[layer][y][x].associatedSprite.spriteHeight,null); } } } } for(int i=0;i(less than)canvasEvents.size();i++){ if(canvasEvents.elementAt(i).condition(this)){ canvasEvents.elementAt(i).run(canvas,this); } } Log.e("JapaneseTutor","Got here.[1]"); drawn=true; Log.e("JapaneseTutor","Got here.[2]"); If you need to see the Timer class, or the full length of the GameHandler or ActualGame classes, just let me know.

    Read the article

  • Changing Data in ListView

    - by legr3c
    Hi In my app I use a ListView to display data from the database. The data changes sometimes, for example when the user applies new filters or changes the sorting method. I use AsyncTask to get the databsase cursor that points to the new data set because sometimes data needs to be loaded from the net which can take some time. What I do now looks something like this: private class updateTask extends AsyncTask<Void, Void, Void> { /* * runs on the UI thread before doInBackground */ @Override protected void onPreExecute(){ // prepare some stuff... } /* * runs in a separate thread * used for time-consuming loading operation */ @Override protected Void doInBackground() { //get new database cursor mCursor = mDbAdapter.getCursor(); return null; } /* * runs on the UI thread after doInBackground */ @Override protected void onPostExecute(Void result){ if(mCursor!=null){ MyActivity.this.startManagingCursor(mCursor); mCursorAdapter = new MyCustomCursorAdapter(MyActivity.this, mCursor); mListView.setAdapter(mCursorAdapter); } } } This works so far but I realize that creating a new CursorAdapter and calling setAdapter on my ListView each time isn't the correct way to do it. Also, after setAdapter the scroll position of the list is set back to the top. I found this post which describes how to do it properly. So now I want to do something like this: onCreate(){ // ... // create the CursorAdapter using null as the initial cursor MyCustomCursorAdapter cursorAdapter = new MyCustomCursorAdapter(this, null); mListView.setAdapter(cursorAdapter); // ... } private class updateTask extends AsyncTask<Void, Void, Void> { /* * runs on the UI thread before doInBackground */ @Override protected void onPreExecute(){ // prepare some stuff... } /* * runs in a separate thread * used for time-consuming loading operation */ @Override protected Void doInBackground() { //get new database cursor mCursor = mDbAdapter.getCursor(); return null; } /* * runs on the UI thread after doInBackground */ @Override protected void onPostExecute(Void result){ // this returns null! MyCustomCursorAdapter cursorAdapter = (MyCustomCursorAdapter)mListView.getAdapter(); Cursor oldCursor = cursorAdapter.getCursor(); if(oldCursor!=null){ MyActivity.this.stopManagingCursor(oldCursor); oldCursor.close(); } if(mCursor!=null){ MyActivity.this.startManagingCursor(mCursor); cursorAdapter.changeCursor(mCursor); } } } This however doesn't work for me because (MyCustomCursorAdapter)mListView.getAdapter(); always returns null. Why does this happen? What am I doing wrong? Edit: Some additional information: my adapter implements SectionIndexer. I don't really think that this has anything to do with my problem but it has caused me some troubles before so I thought I'd mention it.

    Read the article

  • C#: My callback function gets called twice for every Sent Request

    - by Madi D.
    I've Got a program that uploads/downloads files into an online server,Has a callback to report progress and log it into a textfile, The program is built with the following structure: public void Upload(string source, string destination) { //Object containing Source and destination to pass to the threaded function KeyValuePair<string, string> file = new KeyValuePair<string, string>(source, destination); //Threading to make sure no blocking happens after calling upload Function Thread t = new Thread(new ParameterizedThreadStart(amazonHandler.TUpload)); t.Start(file); } private void TUpload(object fileInfo) { KeyValuePair<string, string> file = (KeyValuePair<string, string>)fileInfo; /* Some Magic goes here,Checking The file and Authorizing Upload */ var ftiObject = new FtiObject () { FileNameOnHDD = file.Key, DestinationPath = file.Value, //Has more data used for calculations. }; //Threading to make sure progress gets callback gets called. Thread t = new Thread(new ParameterizedThreadStart(amazonHandler.UploadOP)); t.Start(ftiObject); //Signal used to stop progress untill uploadCompleted is called. uploadChunkDoneSignal.WaitOne(); /* Some Extra Code */ } private void UploadOP(object ftiSentObject) { FtiObject ftiObject = (FtiObject)ftiSentObject; /* Some useless code to create the uri and prepare the ftiObject. */ // webClient.UploadFileAsync will open a thread that // will upload the file and report // progress/complete using registered callback functions. webClient.UploadFileAsync(uri, "PUT", ftiObject.FileNameOnHDD, ftiObject); } I got a callback that is registered to the Webclient's UploadProgressChanged event , however it is getting called twice per sent request. void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e) { FtiObject ftiObject = (FtiObject )e.UserState; Logger.log(ftiObject.FileNameOnHDD, (double)e.BytesSent ,e.TotalBytesToSend); } Log Output: Filename: C:\Text1.txt Uploaded:1024 TotalFileSize: 665241 Filename: C:\Text1.txt Uploaded:1024 TotalFileSize: 665241 Filename: C:\Text1.txt Uploaded:2048 TotalFileSize: 665241 Filename: C:\Text1.txt Uploaded:2048 TotalFileSize: 665241 Filename: C:\Text1.txt Uploaded:3072 TotalFileSize: 665241 Filename: C:\Text1.txt Uploaded:3072 TotalFileSize: 665241 Etc... I am watching the Network Traffic using a watcher, and only 1 request is being sent. Some how i cant Figure out why the callback is being called twice, my doubt was that the callback is getting fired by each thread opened(the main Upload , and TUpload), however i dont know how to test if thats the cause. Note: The reason behind the many /**/ Comments is to indicate that the functions do more than just opening threads, and threading is being used to make sure no blocking occurs (there a couple of "Signal.WaitOne()" around the code for synchronization)

    Read the article

  • How to properly use Object Contexts in Entity Framework using BackgroundWorker

    - by OffApps Cory
    Good day, I am developing using Entity Framework and WPF, and I am encountering some errors and I don't know why. When saving a record (using a BackgroundWorker), I set the entities change tracker to nothing (null), attach the record to a new disposable context, save it, detach, and dispose of the context. Saving a record fires and event in the MainViewModel of the program that the other ViewModels (including the one that is saving) need to refresh their entities to reflect changes. Private Sub _saveRecordWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles _saveRecordWorker.DoWork Using MyContext As New RVShippingEntities Dim MyShipment = CType(ShipmentRecord, IEntityWithChangeTracker) MyShipment.SetChangeTracker(Nothing) MyContext.Attach(MyShipment) MyContext.Detach(ShipmentRecord) End Using End Sub The Refresh background worker is similar, but it has a Do While block to keep it from interfering with the save worker (which doesn't appear to be working; hence the post). When I save (and it subsequently refreshes) I get the following error: The calling thread cannot access this object because a different thread owns it. I thought that with the DoWhile block, it would wait (and when i step through it does) until the save thread finished, and all would be good. But it would seem that something (either the main thread or the save thread) is still doing something that is interfering. Is there a better way of doing this? Am I doing it is a goofy kludgey fashion? Any help would be appreciated. (Apparently Firefox recognized kludgey as a word. Interesting)

    Read the article

  • Customizing Log4j to filter PatternLayout

    - by JavaScriptDude
    Greetings, I have just starting migrating to WLS 10.x and have noticed that the thread name [%t] for WL is quite verbose and more informative than I need for my deployment needs. Ultimately, I only care about the thread ID but WL gives me this:    [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)' ~ Does anybody know if there is a way in log4j to write a custom filter that will allow me to override PatternLayout so I can parse the WLS Thread Name to just output the thread ID which in this case above is 0. I'd rather extend then customize as it makes upgrading libraries so much easier. Thanks :) - JsD

    Read the article

  • Multiple Producers Single Consumer Queue

    - by Talguy
    I am new to multithreading and have designed a program that receives data from two microcontroller measuring various temperatures (Ambient and Water) and draws the data to the screen. Right now the program is singly threaded and its performance SUCKS A BIG ONE. I get basic design approaches with multithreading but not well enough to create a thread to do a task but what I don't get is how to get threads to perform seperate task and place the data into a shared data pool. I figured that I need to make a queue that has one consumer and multiple producers (would like to use std::queue). I have seen some code on the gtkmm threading docs that show a single Con/Pro queue and they would lock the queue object produce data and signal the sleeping thread that it is finished then the producer would sleep. For what I need would I need to sleep a thread, would there be data conflicts if i didn't sleep any of the threads, and would sleeping a thread cause a data signifcant data delay (I need realtime data to be drawn 30 frames a sec) How would I go about coding such a queue using the gtkmm/glibmm library.

    Read the article

  • The simplest concurrency pattern

    - by Ilya Kogan
    Please, would you help me in reminding me of one of the simplest parallel programming techniques. How do I do the following in C#: Initial state: semaphore counter = 0 Thread 1: // Block until semaphore is signalled semaphore.Wait(); // wait until semaphore counter is 1 Thread 2: // Allow thread 1 to run: semaphore.Signal(); // increments from 0 to 1 It's not a mutex because there is no critical section, or rather you can say there is an infinite critical section. So what is it?

    Read the article

  • JUnit terminates child threads

    - by Marco
    Hi to all, When i test the execution of a method that creates a child thread, the JUnit test ends before the child thread and kills it. How do i force JUnit to wait for the child thread to complete its execution? Thanks

    Read the article

  • How to use data receive event in Socket class?

    - by affan
    I have wrote a simple client that use TcpClient in dotnet to communicate. In order to wait for data messages from server i use a Read() thread that use blocking Read() call on socket. When i receive something i have to generate various events. These event occur in the worker thread and thus you cannot update a UI from it directly. Invoke() can be use but for end developer its difficult as my SDK would be use by users who may not use UI at all or use Presentation Framework. Presentation framework have different way of handling this. Invoke() on our test app as Microstation Addin take a lot of time at the moment. Microstation is single threaded application and call invoke on its thread is not good as it is always busy doing drawing and other stuff message take too long to process. I want my events to generate in same thread as UI so user donot have to go through the Dispatcher or Invoke. Now i want to know how can i be notified by socket when data arrive? Is there a build in callback for that. I like winsock style receive event without use of separate read thread. I also do not want to use window timer to for polling for data. I found IOControlCode.AsyncIO flag in IOControl() function which help says Enable notification for when data is waiting to be received. This value is equal to the Winsock 2 FIOASYNC constant. I could not found any example on how to use it to get notification. If i am write in MFC/Winsock we have to create a window of size(0,0) which was just used for listening for the data receive event or other socket events. But i don't know how to do that in dotnet application.

    Read the article

< Previous Page | 78 79 80 81 82 83 84 85 86 87 88 89  | Next Page >