473,668 Members | 2,408 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Wait indefinately for events in C# console app (Threading)

I want to implement a simple console that continuously listens for an
event from a custom object. I am unable to capture the events from
the object.
If I subscribe to the events in a windows app it works fine. Any
idea?

using System;
using MyTestApp.Messa ging;
using MyTestApp.Busin essLayer;
using System.Threadin g;

namespace MyTestApp.Liste ner
{
/// <summary>
/// MyTestApp.Liste ner.Run
/// </summary>
class Run
{
/// <summary>
/// Constructor
/// </summary>
public Run()
{

}

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
Background background = new Background();
Thread th = new Thread(new ThreadStart(bac kground.SpinInf inite));
th.Priority = ThreadPriority. Lowest;
th.Start();

Run run = new Run();
ObjectSubscribe r _ObjSubs = new ObjectSubscribe r("_LOCAL.Test" );
_ObjSubs.Object Received += new ObjectReceivedE vent(run.DoProc ess);

Console.WriteLi ne("Listening") ;
}
catch(Exception ex)
{
Console.WriteLi ne(ex.Message);
Console.ReadLin e();
}
}

/// <summary>
/// This is the event handler
/// </summary>
/// <param name="objTest"> event args</param>
public void DoProcess(objec t objTest)
{
TestObject obj = (TestObject)obj Test;
Console.WriteLi ne("Object Received : ");
Console.WriteLi ne("N1="+ obj.n1);
Console.WriteLi ne("N2="+ obj.n2);
Console.WriteLi ne("STR="+ obj.str);
}
}
}

//----- BACKGROUND.CS---------------------

namespace MyTestApp.TestL istener
{
/// <summary>
/// Background class keeps the process alive.
/// </summary>
public class Background
{
public Background()
{

}

public bool Terminate = false;
public void SpinInfinite()
{
while (!Terminate)
{
Thread.Sleep(ne w TimeSpan(0,0,3) );
}
}
}
}
Nov 15 '05 #1
2 18991
It looks like your main thread is just exiting and the object goes with it.
You need something to keep the main thread alive so that the object is
there.

I'm not sure I understand what this code is supposed to do. It looks like
this code should fire the DoProcess() method exactly once.

I think what you want to do is:

Create a new object.
Create a new thread.
From the thread hook up the event handler on the new object (which was
created on another thread!)
Fire whenever the time comes

Now your event handler should fire but from the worker thread.

How you hook up to the event is going to be important. Usually it's best to
wrap the whole threaded piece into an object so all state goes with the
thread.

+++ Rick ---

--

Rick Strahl
West Wind Technologies
http://www.west-wind.com/
http://www.west-wind.com/wwHelp
----------------------------------
Making waves on the Web
"Gulshan Oshan" <gu***********@ yahoo.com> wrote in message
news:14******** *************** ***@posting.goo gle.com...
I want to implement a simple console that continuously listens for an
event from a custom object. I am unable to capture the events from
the object.
If I subscribe to the events in a windows app it works fine. Any
idea?

using System;
using MyTestApp.Messa ging;
using MyTestApp.Busin essLayer;
using System.Threadin g;

namespace MyTestApp.Liste ner
{
/// <summary>
/// MyTestApp.Liste ner.Run
/// </summary>
class Run
{
/// <summary>
/// Constructor
/// </summary>
public Run()
{

}

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
Background background = new Background();
Thread th = new Thread(new ThreadStart(bac kground.SpinInf inite));
th.Priority = ThreadPriority. Lowest;
th.Start();

Run run = new Run();
ObjectSubscribe r _ObjSubs = new ObjectSubscribe r("_LOCAL.Test" );
_ObjSubs.Object Received += new ObjectReceivedE vent(run.DoProc ess);

Console.WriteLi ne("Listening") ;
}
catch(Exception ex)
{
Console.WriteLi ne(ex.Message);
Console.ReadLin e();
}
}

/// <summary>
/// This is the event handler
/// </summary>
/// <param name="objTest"> event args</param>
public void DoProcess(objec t objTest)
{
TestObject obj = (TestObject)obj Test;
Console.WriteLi ne("Object Received : ");
Console.WriteLi ne("N1="+ obj.n1);
Console.WriteLi ne("N2="+ obj.n2);
Console.WriteLi ne("STR="+ obj.str);
}
}
}

//----- BACKGROUND.CS---------------------

namespace MyTestApp.TestL istener
{
/// <summary>
/// Background class keeps the process alive.
/// </summary>
public class Background
{
public Background()
{

}

public bool Terminate = false;
public void SpinInfinite()
{
while (!Terminate)
{
Thread.Sleep(ne w TimeSpan(0,0,3) );
}
}
}
}

Nov 15 '05 #2
Thanks Rick,

It worked! I created a worker thread like you described and
instantiated and subscribed to events in it. I kept background thread
to keep the console app alive. I dont understand why I couldnt
subscribe to events in the Main method of the console app. Anything
to do with STAThread?

Some background in case you are wondering what I am trying to get
done. What I had been trying to do was listen to Tibco messages from
this console app. It was a sort of test for me to get a feel for
Tibco and to consider using it as a more reliable and simpler way of
distributed computing. I serialize objects and send them over the
network via Tibco as opaque bytes to load balanced queues (Tibco
Distributed Queues). On the receiving end I get appropriate events,
deserialize object and work with it.

Thanks again
Gulshan S. Oshan


"Rick Strahl [MVP]" <ri********@hot mail.com> wrote in message news:<OK******* *******@TK2MSFT NGP09.phx.gbl>. ..
It looks like your main thread is just exiting and the object goes with it.
You need something to keep the main thread alive so that the object is
there.

I'm not sure I understand what this code is supposed to do. It looks like
this code should fire the DoProcess() method exactly once.

I think what you want to do is:

Create a new object.
Create a new thread.
From the thread hook up the event handler on the new object (which was
created on another thread!)
Fire whenever the time comes

Now your event handler should fire but from the worker thread.

How you hook up to the event is going to be important. Usually it's best to
wrap the whole threaded piece into an object so all state goes with the
thread.

+++ Rick ---

--

Rick Strahl
West Wind Technologies
http://www.west-wind.com/
http://www.west-wind.com/wwHelp
----------------------------------
Making waves on the Web
"Gulshan Oshan" <gu***********@ yahoo.com> wrote in message
news:14******** *************** ***@posting.goo gle.com...
I want to implement a simple console that continuously listens for an
event from a custom object. I am unable to capture the events from
the object.
If I subscribe to the events in a windows app it works fine. Any
idea?

using System;
using MyTestApp.Messa ging;
using MyTestApp.Busin essLayer;
using System.Threadin g;

namespace MyTestApp.Liste ner
{
/// <summary>
/// MyTestApp.Liste ner.Run
/// </summary>
class Run
{
/// <summary>
/// Constructor
/// </summary>
public Run()
{

}

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
Background background = new Background();
Thread th = new Thread(new ThreadStart(bac kground.SpinInf inite));
th.Priority = ThreadPriority. Lowest;
th.Start();

Run run = new Run();
ObjectSubscribe r _ObjSubs = new ObjectSubscribe r("_LOCAL.Test" );
_ObjSubs.Object Received += new ObjectReceivedE vent(run.DoProc ess);

Console.WriteLi ne("Listening") ;
}
catch(Exception ex)
{
Console.WriteLi ne(ex.Message);
Console.ReadLin e();
}
}

/// <summary>
/// This is the event handler
/// </summary>
/// <param name="objTest"> event args</param>
public void DoProcess(objec t objTest)
{
TestObject obj = (TestObject)obj Test;
Console.WriteLi ne("Object Received : ");
Console.WriteLi ne("N1="+ obj.n1);
Console.WriteLi ne("N2="+ obj.n2);
Console.WriteLi ne("STR="+ obj.str);
}
}
}

//----- BACKGROUND.CS---------------------

namespace MyTestApp.TestL istener
{
/// <summary>
/// Background class keeps the process alive.
/// </summary>
public class Background
{
public Background()
{

}

public bool Terminate = false;
public void SpinInfinite()
{
while (!Terminate)
{
Thread.Sleep(ne w TimeSpan(0,0,3) );
}
}
}
}

Nov 15 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

29
4219
by: Paul L. Du Bois | last post by:
Has anyone written a Queue.Queue replacement that avoids busy-waiting? It doesn't matter if it uses os-specific APIs (eg WaitForMultipleObjects). I did some googling around and haven't found anything so far. Because I know someone will ask: no, the busy-waiting hasn't been a problem in my app. I'm just interested in reading the code. p
28
1869
by: Dennis Owens | last post by:
I am trying to run a thread off of a form, and every once in a while the thread will raise an event for the form to read. When the form gets the event, the form will place the event into a dataset and display it on a datagrid that is on the form. The problem is that the thread will slowly take over all of the processor time. After about 8 events, the form will not even respond anymore. Here is the guts of my test code // Class and event for...
3
4777
by: mvdevnull | last post by:
static void Main(string args) { DoSomething(); } static void DoSomething() { for (int i=0; i<=10; i++) { CallAsyncMethod(); } } my problem is when i run the app console exists without really completing DoSomething() if i add 'Console.ReadLine() to Main() then console waits until
11
2928
by: Michi Henning | last post by:
Hi, I'm calling Monitor.Wait() from a console event handler. It's not working -- the call to Wait() immediately causes the process to exit. Is it impossible for some reason to call Wait() from an event handler? Small code example attached. Thanks,
3
506
by: Jacob | last post by:
I'm working on a class that needs to be called from a windows form, do it's work, and then, show progress back to the main form. I'm well aware that worker threads need to call Invoke for updates to the main thread to be threadsafe. I want to make this worker class I'm writing a self contained assembly so that other's can drop it into their projects. My question is: How can I NOT force those implementing my class to have to call...
8
2641
by: Danny Tuppeny | last post by:
Hi All, I've written a console app, which sends and recieves data across a NetworkStream and displays output to the console. All is great. I'm now modifying it to be a windows app, but the thing blocks while waiting to recieve data. So, I want to run it in a thread. However, the object that's running my events fires events, and these all need to update the UI. What's the best way of doing this? Should I call BeginInvoke from inside my...
6
2436
by: SP | last post by:
Hi, I want to add wait cursor code whenever page is post back. Page may be post back on my user control's or on change of dropdown or on click of any button on page. so is there any common solution available that will provide me mechanism to display wait cursor or wait image to user whenever page is post back to server? Thanks,
1
1328
by: myregid | last post by:
I am developing an application which used DigitalPersona gold SDK 2.4 under VB.net 2003. ---------------------------------------------------------- api in C++ ¡¾FT_startMonitoringDevice¡¿ FT_RETCODE FT_startMonitoringDevice( IN FT_HANDLE ftContext, /* device context */ IN FT_DEVICE_EVENTS_PT events); /* events handle */
4
3990
by: Sid Price | last post by:
Hello, I have a class of objects (Device) that are managed by another object (Devices) with a collection class (DeviceCollection) inherited from Collections.Hashtable. Each of the Device objects can raise an event and I need the managing class (Devices) to be able to catch these events. Public Class Device Public Event StatusChange()
0
8462
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8802
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8586
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7405
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5682
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4206
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4384
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2028
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1787
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.