c#: how terminate a background thread in dispose() method? - multithreading

I have a program which runs a thread. The thread performs processing all the time and it uses some synchronized queue.
The class snapshot is as follows:
public class MyClass:IDisposable
{
private Thread myThread = new Thread(threadFunc);
private volatile bool runThread = true;
public MyClass()
{
myThread.Start();
}
public Dispose()
{
runThread = false;
}
private void threadFunc()
{
try
{
while(runThread){
queue.Take(); //This method blocks the thread if queue is empty. It uses Monitor class
//do some processing
}
}
catch(Exception e){...}
}
private void otherFunc()
{
queue.enqueue(...);//this method is executed by main thread and uses lock while adding element to the queue.
}
}
When I call Dispose() method, the thread exists threadFunc() method, but after a sec I get an execption from this func "Unable to avaluate expression...", as if the tread was terminated while doing some work. Maybe it has just released from queue.Take() blocking and has no context to run. I know I'm missing something...
How can I solve such problem and terminate the thread from the Dispose method.
Many thanks!!!

Use the overload of Take that accepts a CancellationToken. You can get a reference to a token by using the CancellationTokenSource which also has the Cancel method that you can call from Dispose to unblock the Take method. You can read more cancellation here.

Use the poison pill approach: See this thread

Related

check asynchronous threads state in java

I have method in class MyClassB which is triggered asynchronously from a method of MyClassA:
public void getProductCall()
{
new Thread(new Runnable() {
#Override
public void run() {
try {
productRequest = service.createS4ProductRequest(getRepriceItems());
//Below is a rest call to another system
String response = pricing.getS4ProductResponse(quote.getAssetQuoteNrAndVrsn(), productRequest);
//I'm using the below 2 lines to check from ClassA's method to see if this process has ended
setProductResponse(response);
productPriceProcessEnded=true;
} catch (Exception e) {
productPriceErrorOccured=true;
e.printStackTrace();
}
}
}).start();
}
This is the piece of code in MyClassA i used to check if the above method is complete.
for(int i=0;i<1000000000;i++)
{
if(!networkAsynCalls.isListPriceErrorOccured())
{
if(networkAsynCalls.isListPriceprocessEnded())
{
return networkAsynCalls.getListReponse();
}
else
{
Thread.sleep(250);
continue;
}
}
else
return null;
}
instead of using this random for loop can i use some inbuilt method or service pool or something ?
Because,
1) This thread on method is in another class
2) In class MyClassB i have few more methods like this, so i need to check the status of all the methods in MyClassA
Thanks for any help.
If I undestand what you're trying to do is dispatch some code to be ran asynchronously, then be able to wait until it is completed (successfully or failed). If that's the case, you should take a look at Futures.
Here is an example based on the Javadoc:
FutureTask<String> future =
new FutureTask<String>(new Callable<String>() {
public String call() {
// do stuff
return "result";
}});
This code creates an object "future" that can be invoked to execute searcher.search(target). At this point, the code is not executed at all. You simply have an object representing a computation that may be executed asynchronously. To do so, you'd call:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(future);
This snippet created an Executor (which is a fixed pool of 5 threads), then handed over the future to it for execution. The executor will run the computation from Future asynchronously.
Future offers some methods (see the Javadoc) to wait until completion, cancel, check completion status, etc. For example,
String result = future.get();
will block, waiting for the result indefinitely. A get(10, TimeUnit.SECONDS) will wait for 10 seconds and if the future has not completed, throw.

Multithreading: Same two object is entering into synchronized block

May be my header would not be correct.
I have started java multithread concept with programming. since i have read inside synchronized block only one thread will inter on a particular object lock. But i have confused after looking the output of this program.
package com.example.classandobjectlevellock;
class MyThread implements Runnable
{
Object ob = new Object();
public void run() {
synchronized (this) {
System.out.println(Thread.currentThread().getName()+" Is waitng");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ClassAndObjectLevelLock {
public static void main(String[] args) throws InterruptedException {
MyThread task1 = new MyThread();
MyThread task2 = new MyThread();
Thread t1 = new Thread(task1,"Thread1");
Thread t2 = new Thread(task1,"Thread2");
Thread t3 = new Thread(task2,"Thread3");
t1.start();
Thread.sleep(1000);
t2.start();
Thread.sleep(1000);
t3.start();
}
}
Output:
Thread1 Is waitng
Thread2 Is waitng
Thread3 Is waitng
If i am not wrong, Thread-1 and thread-3 is entering into synchronized method because it having two different target object. But why Thread-2 is entering into Synchronized block?
Please help me for understanding of this .
Thanks in advance.
Calling wait() causes the lock to be released.
Per the wait() Javadocs:
Causes the current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object. In
other words, this method behaves exactly as if it simply performs the
call wait(0).
The current thread must own this object's monitor. The thread
releases ownership of this monitor and waits until another thread
notifies threads waiting on this object's monitor to wake up either
through a call to the notify method or the notifyAll method. The
thread then waits until it can re-obtain ownership of the monitor and
resumes execution.

What is the purpose of await() in CountDownLatch?

I have the following program, where I am using java.util.concurrent.CountDownLatch and without using await() method it's working fine.
I am new to concurrency and want to know the purpose of await(). In CyclicBarrier I can understand why await() is needed, but why in CountDownLatch?
Class CountDownLatchSimple:
public static void main(String args[]) {
CountDownLatch latch = new CountDownLatch(3);
Thread one = new Thread(new Runner(latch),"one");
Thread two = new Thread(new Runner(latch), "two");
Thread three = new Thread(new Runner(latch), "three");
// Starting all the threads
one.start(); two.start(); three.start();
}
Class Runner implements Runnable:
CountDownLatch latch;
public Runner(CountDownLatch latch) {
this.latch = latch;
}
#Override
public void run() {
System.out.println(Thread.currentThread().getName()+" is Waiting.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
System.out.println(Thread.currentThread().getName()+" is Completed.");
}
OUTPUT
two is Waiting.
three is Waiting.
one is Waiting.
one is Completed.
two is Completed.
three is Completed.
CountDownLatch is the synchronization primitive which is used to wait for all threads completing some action.
Each of the thread is supposed to mark the work done by calling countDown() method. The one who waits for the action to be completed should call await() method. This will wait indefinitely until all threads mark the work as processed, by calling the countDown(). The main thread can then continue by processing the worker's results for example.
So in your example it would make sense to call await() at the end of main() method:
latch.await();
Note: there are many other use cases of course, they don't need to be threads but whatever that runs usually asynchronously, the same latch can be decremented several times by the same task etc. The above describes just one common use case for CountDownLatch.

Windows service & mutilthreading

I have a windows service, which is executed regular intervals... Here is the code snippet:
protected override void OnStart(string[] args)
{
tickTack = new Timer(10000);
tickTack.Elapsed += new ElapsedEventHandler(tickTack_Elapsed);
tickTack.Start();
}
protected override void OnStop()
{
tickTack.Stop();
}
private void tickTack_Elapsed(object sender, ElapsedEventArgs e)
{
objProc = new Processing();
objProc.start();
}
In my start() method of Processing Class do my actual work like below.
public void start()
{
try
{
Process_Requests();
Process_Exports();
}
catch (Exception ex)
{
ErrorLogs.SaveError(ex, "");
}
}
How does the execution is happen when the execution done in a single thread??? For example, the first method takes time for execution then what about second method????
Now I want to call Process_request() and Preocess_export() methods. Each method should connect to multiple databases. In this situation, would I need to create new thread for each connection and do my work... I am not sure.
public void start()
{
try
{
#region
sqlConObjects = new List<SqlConnection>();
// Here i am getting multiple connection strings
List<string> conStrings = GetConnectionStrings();
foreach (string strCon in conStrings)
{
SqlConnection sqlCon = new SqlConnection(strCon);
sqlConObjects.Add(sqlCon);
}
foreach (SqlConnection sqlCon in sqlConObjects)
{
//sqlCon.Open();
Thread t = new Thread(ProcessRequest);
t.Start((object)sqlCon);
Thread t1=new Thread(ProcessExports);
t1.Start((object)sqlCon);
}
#endregion
}
catch (Exception ex)
{
ErrorLogs.SaveError(ex, "");
}
}
Can anyone please explain how to do this... is thread is created or no need??? How should the execution is happen if we are not creating a thread for each connection object.
Timer works on ThreadPool
From MSDN
The callback method executed by the timer should be reentrant, because it is called on ThreadPool threads. The callback can be executed simultaneously on two thread pool threads if the timer interval is less than the time required to execute the callback, or if all thread pool threads are in use and the callback is queued multiple times.
Also in your's code you don't keep reference to timer object and it will be collected.
As for me you should use ThreadPool. Createing a lot of threads is bad practice

Thread Invalid Access Error in SWT

Could you let me know the reason for this error in SWT
"org.eclipse.swt.SWTException" Invalid Thread access ?
And How to fix such errors.
It happens when you try to act upon an interface item from a thread that's not the UI thread.
To run a code on the UI thread you have to use a Runnable and ask the display thread to run it. This way:
Display.getDefault().syncExec( new Runnable() {
#Override
public void run() {
// Do your job here
}
} );
As stated by the syncExec method javadoc,
the thread which calls this method is suspended until the runnable completes.
Also, you might check the asyncExec method.
In SWT you can access GUI resources only from the display thread. For example when setting the text in a org.eclipse.swt.widgets.Text control you must already be in the display thread or call
final Text text = ...;
Display.getCurrent().syncExec(new Runnable() {
#Override
public void run() {
text.setText("test");
}
});

Resources