473,698 Members | 2,598 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# threading & events

Hi NG.

I'm creating a little app. that has to use a 3rd party API.
The functions in this API has no return value but trigger events like OK
or NOT OK with event args.

Where I need to use this API I must have a synchrone modul so I need to
force a synchrone look to this asynchrone model of the API.

I was thinking this would call for some waiting for events and since I
don't wanna make a loop eat all the cpu power I was thinking of using a
few threads to accomplish this.

It's giving me some trouble though I'm aware it's a pretty common and
simple scenario.

I was hoping maybe somone here could lend me a hand.

What I need is as said, to make some code that uses the API but my code
has to be synchrone while the API is not.

So I can do somthing like:
--------------------------
public MyClass
{
private bool InProcess;
private bool ItWentWell;

public bool Function1()
{
InProcess = true;

APIClass apic = new APIClass();

apic.FunctionAP I1_Success += EventHandler(Fu nctionOK);
apic.FunctionAP I1_Failed += EventHandler(Fu nctionERROR);

apic.FunctionAP I1();

...
Wait for InProcess to change from TRUE to FALSE.
Once this happens, return ItWentWell.
}

public void FunctionOK()
{
Inprocess = false;

ItWentWell = true;
}

public void FunctionERROR()
{
InProcess = false;

ItWentWell = false;
}
}

//--- somwhere like the Main of a console app. ---
MyClass mc = new MyClass();

if(mc.Function1 ())
{
Consile.WriteLi ne("API call went well.");
}
else
{
Consile.WriteLi ne("API call went bad.")
}
--------------------------

I'm aware that the above doesn't work, it's only to give a picture of
what I'm trying to accomplish. Somwhere around the part with the waiting
for the event to occur should most likely be using a new thread not to
eat all the cpu power, but I can't get the things I've tried to work.

Any help would be much appreciated, thanks :)

/Aidal
Jan 11 '07 #1
12 2243

"Aidal" <no@address.com wrote in message
news:45******** *************@d reader2.cyberci ty.dk...
Hi NG.

I'm creating a little app. that has to use a 3rd party API.
The functions in this API has no return value but trigger events like OK
or NOT OK with event args.

Where I need to use this API I must have a synchrone modul so I need to
force a synchrone look to this asynchrone model of the API.

I was thinking this would call for some waiting for events and since I
don't wanna make a loop eat all the cpu power I was thinking of using a
few threads to accomplish this.
Use the EventWaitHandle class built in to .NET. Or convert your algorithm
to a state machine.
Jan 11 '07 #2
Aidal skrev:
Hi NG.

I'm creating a little app. that has to use a 3rd party API.
The functions in this API has no return value but trigger events like OK
or NOT OK with event args.

Where I need to use this API I must have a synchrone modul so I need to
force a synchrone look to this asynchrone model of the API.

I was thinking this would call for some waiting for events and since I
don't wanna make a loop eat all the cpu power I was thinking of using a
few threads to accomplish this.

It's giving me some trouble though I'm aware it's a pretty common and
simple scenario.

I was hoping maybe somone here could lend me a hand.

What I need is as said, to make some code that uses the API but my code
has to be synchrone while the API is not.

So I can do somthing like:
--------------------------
public MyClass
{
private bool InProcess;
private bool ItWentWell;

public bool Function1()
{
InProcess = true;

APIClass apic = new APIClass();

apic.FunctionAP I1_Success += EventHandler(Fu nctionOK);
apic.FunctionAP I1_Failed += EventHandler(Fu nctionERROR);

apic.FunctionAP I1();

...
Wait for InProcess to change from TRUE to FALSE.
Once this happens, return ItWentWell.
}

public void FunctionOK()
{
Inprocess = false;

ItWentWell = true;
}

public void FunctionERROR()
{
InProcess = false;

ItWentWell = false;
}
}

//--- somwhere like the Main of a console app. ---
MyClass mc = new MyClass();

if(mc.Function1 ())
{
Consile.WriteLi ne("API call went well.");
}
else
{
Consile.WriteLi ne("API call went bad.")
}
--------------------------

I'm aware that the above doesn't work, it's only to give a picture of
what I'm trying to accomplish. Somwhere around the part with the waiting
for the event to occur should most likely be using a new thread not to
eat all the cpu power, but I can't get the things I've tried to work.

Any help would be much appreciated, thanks :)

/Aidal
Anyone have an actual code example or a link to one where:

Class1.Function A calls Class2.Function B which will (at some point)
trigger an event.
Class1.Function A must not return before the event occuers because it
needs to base its return value on what the event "said" like true/false.

Aka Class1.Function A must wait for the event triggered by
Class2.Function B to occuer before it knows what to return.

As mentioned above I assume some threading should be used but I'm not sure.

/Aidal
Jan 12 '07 #3
Like so?

using System;
using System.Threadin g;

static class Program
{
static void Main()
{
new ClassA().Method A();
}
}
class ClassA
{
public void MethodA()
{
ClassB b = new ClassB();
string theSomething = "";
ManualResetEven t evt = new ManualResetEven t(false);
b.SomethingHapp ened += delegate
{
theSomething = b.TheSomething;
evt.Set();
};
ThreadPool.Queu eUserWorkItem(d elegate {
b.MethodB();
});
evt.WaitOne();
Console.WriteLi ne(theSomething );
}
}
class ClassB
{
public event EventHandler SomethingHappen ed;
private string _theSomething;
public string TheSomething {get {return _theSomething;} }
protected void OnSomethingHapp ened()
{
EventHandler handler = SomethingHappen ed;
if (handler != null) handler(this, EventArgs.Empty );
}
public void MethodB()
{
_theSomething = Console.ReadLin e();
OnSomethingHapp ened();
}
}
Jan 12 '07 #4
Note: for brevity, in my example I didn't bother putting the "what
happened" into an event-arg subclass - but this would work identically
to the property approach; you may also wish to be "using" the
ManualResetEven t (since it is IDisposable).

As an alternative, note that you can also do this using locks to avoid
the (marginally more expensive) ManualResetEven t - but unless you are
high volume it might not be worth it; note to follow the logic here
requires a good understanding of "lock" (Monitor.Enter, Monitor.Exit),
Monitor.Wait and Monitor.Pulse.. .

public void MethodA() {
ClassB b = new ClassB();
string theSomething = "";
object sync = new object();
b.SomethingHapp ened += delegate {
theSomething = b.TheSomething;
lock (sync) {
Monitor.Pulse(s ync);
}
};
lock (sync) {
ThreadPool.Queu eUserWorkItem(d elegate {
b.MethodB();
});
Monitor.Wait(sy nc);
}
Console.WriteLi ne(theSomething );
}
Jan 12 '07 #5
Marc Gravell skrev:
Like so?

using System;
using System.Threadin g;

static class Program
{
static void Main()
{
new ClassA().Method A();
}
}
class ClassA
{
public void MethodA()
{
ClassB b = new ClassB();
string theSomething = "";
ManualResetEven t evt = new ManualResetEven t(false);
b.SomethingHapp ened += delegate
{
theSomething = b.TheSomething;
evt.Set();
};
ThreadPool.Queu eUserWorkItem(d elegate {
b.MethodB();
});
evt.WaitOne();
Console.WriteLi ne(theSomething );
}
}
class ClassB
{
public event EventHandler SomethingHappen ed;
private string _theSomething;
public string TheSomething {get {return _theSomething;} }
protected void OnSomethingHapp ened()
{
EventHandler handler = SomethingHappen ed;
if (handler != null) handler(this, EventArgs.Empty );
}
public void MethodB()
{
_theSomething = Console.ReadLin e();
OnSomethingHapp ened();
}
}

I've tried to create your example but it appears to have syntax errors
around "b.SomthingHapp ened += delegate". :(

/Aidal
Jan 12 '07 #6
Marc Gravell skrev:
Like so?

using System;
using System.Threadin g;

static class Program
{
static void Main()
{
new ClassA().Method A();
}
}
class ClassA
{
public void MethodA()
{
ClassB b = new ClassB();
string theSomething = "";
ManualResetEven t evt = new ManualResetEven t(false);
b.SomethingHapp ened += delegate
{
theSomething = b.TheSomething;
evt.Set();
};
ThreadPool.Queu eUserWorkItem(d elegate {
b.MethodB();
});
evt.WaitOne();
Console.WriteLi ne(theSomething );
}
}
class ClassB
{
public event EventHandler SomethingHappen ed;
private string _theSomething;
public string TheSomething {get {return _theSomething;} }
protected void OnSomethingHapp ened()
{
EventHandler handler = SomethingHappen ed;
if (handler != null) handler(this, EventArgs.Empty );
}
public void MethodB()
{
_theSomething = Console.ReadLin e();
OnSomethingHapp ened();
}
}

The actual scenario is:
=============== ========
ClassAPI has a function
- void SendFile()
and the two events
- FileSendOK
and
- FileSendError

MyClass has the function
- bool SendFile()
which is to use the function ClassAPI.SendFi le()

What I want to be able to do is:
--------------------------------
MyClass mc = new MyClass();

if(mc.SendFile( ))
{
do somthing when sending file is successful...
}
else
{
do somthing else when sending file fails...
}
---------------------------------

Which means MyClass.SendFil e() must wait for one of the two events in
ClassAPI to occuer (due to the ClassAPI.SendFi le call) before it returns.

/Aidal
Jan 12 '07 #7
Ah... 1.1... I was heavily using the "captured variable" feature of
anonymous methods as a means to share state between threads. Never
mind... it can be done the other way - it just takes more code. Note:
I hanve't tested this in 1.1, so it may need tweaking, but it should
be fairly close (may also need to lose "static" from "static class
Program"):

class ClassA
{
internal class MethodAState
{
private readonly ClassB B;
private readonly object Sync = new object();
private string _theSomething;
public MethodAState()
{
B = new ClassB();
B.SomethingHapp ened += new
EventHandler(B_ SomethingHappen ed);
}
public string StartAndWaitMet hodB()
{
lock (Sync)
{
ThreadPool.Queu eUserWorkItem(n ew
WaitCallback(B_ StartB));
Monitor.Wait(Sy nc);
return _theSomething;
}
}
void B_StartB(object state)
{
B.MethodB();
}

void B_SomethingHapp ened(object sender, EventArgs e)
{
lock (Sync)
{
_theSomething = B.TheSomething;
Monitor.Pulse(S ync);
}
}

}
public void MethodA()
{
MethodAState state = new MethodAState();
string value = state.StartAndW aitMethodB();
Console.WriteLi ne(value);
}
}
Jan 12 '07 #8
Previous post re-worked to handle two different events with differing
signatures (pretend that TheSomething is in the event-args <g>). Type
"boom" to get the new behaviour; the string could likewise be a
success bool:

using System;
using System.Threadin g;

class Program
{
static void Main()
{
new ClassA().Method A();
}
}
class ClassA
{
internal class MethodAState
{
private readonly ClassB B;
private readonly object Sync = new object();
private string _theSomething;
public MethodAState()
{
B = new ClassB();
B.SomethingHapp ened += new
EventHandler(B_ SomethingHappen ed);
B.SomethingElse Happened +=new
EventHandler(B_ SomethingElseHa ppened);
}
public string StartAndWaitMet hodB()
{
lock (Sync)
{
ThreadPool.Queu eUserWorkItem(n ew
WaitCallback(B_ StartB));
Monitor.Wait(Sy nc);
return _theSomething;
}
}
void B_StartB(object state)
{
B.MethodB();
}

void B_SomethingHapp ened(object sender, EventArgs e)
{
ReleaseCaller(B .TheSomething);
}
void B_SomethingElse Happened(object sender, EventArgs e)
{
ReleaseCaller(" PANIC PANIC PANIC");
}
private void ReleaseCaller(s tring result)
{
lock (Sync)
{
_theSomething = result;
Monitor.Pulse(S ync);
}
}

}
public void MethodA()
{
MethodAState state = new MethodAState();
string value = state.StartAndW aitMethodB();
Console.WriteLi ne(value);
}
}
class ClassB
{
public event EventHandler SomethingHappen ed,
SomethingElseHa ppened;
private string _theSomething;
public string TheSomething { get { return _theSomething; } }
private void OnEvent(EventHa ndler handler)
{
if (handler != null) handler(this, EventArgs.Empty );
}
public void MethodB()
{
string value = Console.ReadLin e();
if (value == "boom")
{
OnEvent(Somethi ngElseHappened) ;
}
else
{
_theSomething = value;
OnEvent(Somethi ngHappened);
}
}
}
Jan 12 '07 #9
Marc Gravell skrev:
Previous post re-worked to handle two different events with differing
signatures (pretend that TheSomething is in the event-args <g>). Type
"boom" to get the new behaviour; the string could likewise be a
success bool:

using System;
using System.Threadin g;

class Program
{
static void Main()
{
new ClassA().Method A();
}
}
class ClassA
{
internal class MethodAState
{
private readonly ClassB B;
private readonly object Sync = new object();
private string _theSomething;
public MethodAState()
{
B = new ClassB();
B.SomethingHapp ened += new
EventHandler(B_ SomethingHappen ed);
B.SomethingElse Happened +=new
EventHandler(B_ SomethingElseHa ppened);
}
public string StartAndWaitMet hodB()
{
lock (Sync)
{
ThreadPool.Queu eUserWorkItem(n ew
WaitCallback(B_ StartB));
Monitor.Wait(Sy nc);
return _theSomething;
}
}
void B_StartB(object state)
{
B.MethodB();
}

void B_SomethingHapp ened(object sender, EventArgs e)
{
ReleaseCaller(B .TheSomething);
}
void B_SomethingElse Happened(object sender, EventArgs e)
{
ReleaseCaller(" PANIC PANIC PANIC");
}
private void ReleaseCaller(s tring result)
{
lock (Sync)
{
_theSomething = result;
Monitor.Pulse(S ync);
}
}

}
public void MethodA()
{
MethodAState state = new MethodAState();
string value = state.StartAndW aitMethodB();
Console.WriteLi ne(value);
}
}
class ClassB
{
public event EventHandler SomethingHappen ed,
SomethingElseHa ppened;
private string _theSomething;
public string TheSomething { get { return _theSomething; } }
private void OnEvent(EventHa ndler handler)
{
if (handler != null) handler(this, EventArgs.Empty );
}
public void MethodB()
{
string value = Console.ReadLin e();
if (value == "boom")
{
OnEvent(Somethi ngElseHappened) ;
}
else
{
_theSomething = value;
OnEvent(Somethi ngHappened);
}
}
}

Thanks Marc :)

This example looks very interesting, I will try to apply the idea to my
code as soon as I get a free moment from other stuff.

/Aidal
Jan 15 '07 #10

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

Similar topics

77
5274
by: Jon Skeet [C# MVP] | last post by:
Please excuse the cross-post - I'm pretty sure I've had interest in the article on all the groups this is posted to. I've finally managed to finish my article on multi-threading - at least for the moment. I'd be *very* grateful if people with any interest in multi-threading would read it (even just bits of it - it's somewhat long to go through the whole thing!) to check for accuracy, effectiveness of examples, etc. Feel free to mail...
4
4089
by: Bardo | last post by:
Hi, I have a situation where I am capturing both a WMI event utilising the "ManagementEventWatcher" in the "System.Management" namespace, and a corresponding event ("EntryWritten") raised from the "EventLog" object in the "System.Diagnostics" namespace. When a certain event occurrs, both a WMI event is raised, and an event log entry is written. The problem I have is that I need to capture both events and somehow correlate which WMI...
6
3258
by: MPH Computers | last post by:
Hi I am looking for some help on Threading and Critical Sections I have a main thread that controls an event the event handler creates a new thread for carrying out the work because the work may not be completed before the event is triggered again I am trying to add critical sections round the producer & consumer parts of
5
2362
by: Andrew Lippitt | last post by:
What gaurantees are there in the way of which thread the events are called from. I've seen: Thread A Begin Thread B Begin Thread A End Thread A End That seems to indicate that Begin and End can't be assumed to be called from the same thread, but can I assume that the Begin will happen on the same thread that executes the request?
2
1664
by: elziko | last post by:
I have an object (Object1) that instantiates another class (Object2) in a seperate thread. It must be in its own thread for an ActiveX control it hosts to work. From Object1 I can get to all the methods of the ActiveX control in Object2 which is fine. However, I need to get some information back from Object2 as its state changes. How would I go about informing Object1 of events that occur in the ActiveX control? At the moment I'm...
0
984
by: BenLeino | last post by:
Hi out there, I have a little problem with threading an event receiving. I have a custom Class (DLL) that raises Events. When I run the Instance without threading it works fine. When I do threading no Events are received. Code:
13
1942
by: Bob | last post by:
My WinForms app runs on the single default thread, and uses a single SqlConnection object for all queries. I need to use one or more timers to periodically execute some of them. My own testing indicates that the forms timer does not operate on its own thread and will not cause a query to be sent to use the single SqlConnection while another is being executed from the handling of other events. Is that right? I just want to be 100% sure...
5
1274
by: Spam Catcher | last post by:
Hi all When .NET fires and event, does the event handler execute under a new thread, or does it execute under the primary application thread? Basically if I have events firing, do the event handlers themselves need to spawn need threads, or can I safely assume the event handler is already running under a new thread?
5
3512
by: JasonX | last post by:
Im having problems with my program, in that if I close the main form while my new thread is doing work which involves writing to the main form, then I get an error about a disposed object. To fix this, i have added an event, with the aim the main form subscribes to the event when it is created and unsubscribes as soon as its closed. This approach however has not fixed the problem. When the event is raised, it writes to the form using a...
0
8680
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
8609
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8899
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
8871
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6528
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4371
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
4622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2335
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
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.