473,789 Members | 2,254 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Synchronizing processes in C#

I have the following situation:

Process 1 creates Process 2 (using Process.Start(s tartInfo)
Process 1 needs to wait until Process 2 is initialized before Process 1 can continue to execute
Both processes are non-GUI processes.

The problem that I am running into is that the Process.Start(s tartInfo) returns immediately to Process 1. Therefore, process 1 does not wait on its own for Process 2 to initialize.

Process 2 can take a few seconds to intialize. Process 1 needs to halt its execution until Process 2 is initialized. How can process 1 and 2 signal eachother to accomplish what I'm after?

In process 1 I tried using a Mutex:

Process process = Process.Start(s tartInfo);

if (process != null)
{
Mutex m = new Mutex(false, "Mutex");
m.WaitOne();
...
}

Process 2:

Main...
{
bool mutexWasCreated = false;
Mutex m = new Mutex(true, "Mutex", out mutexWasCreated );
if (mutexWasCreate d)
{
...
m.ReleaseMutex( );
}
}

this doesn't come close to working because process 1 gets the mutex before process 2 can acquire the lock. What I need is the ability to have process 1 wait on a mutex, have process 2 acquire the mutex lock, do its initialization, then release the mutex, then process 1 resumes execution.

I have gotten the above to work in C++ using the CreateEvent API. Process 1 creates an unsignaled event, process 1 launches process 2, process 1 waits on the event, process 2 does its thing, process 2 signals the event, process 1 continues.

How can I do this in C#?

Thanks!

Nov 16 '05 #1
5 2071
You can use P/Invoke to access the Win32 CreateEvent API to create named
events. I created this test app fairly quicklly that seems to work...

in project 1
using System;
using System.Diagnost ics;
using System.Threadin g;
using System.Runtime. InteropServices ;

namespace ConsoleApplicat ion1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
[DllImport("kern el32.dll", SetLastError=tr ue)]
static extern IntPtr CreateEvent(Int Ptr lpEventAttribut es, bool
bManualReset,
bool bInitialState, string lpName);

[DllImport("kern el32.dll")]
static extern bool SetEvent(IntPtr hEvent);

[DllImport("kern el32.dll")]
static extern bool ResetEvent(IntP tr hEvent);
[DllImport("kern el32.dll", SetLastError=tr ue)]
static extern int CloseHandle(Int Ptr hObject);

const int ERROR_ALREADY_E XISTS = 183;
/// <summary>
///
/// </summary>
[STAThread]
static void Main(string[] args)
{
string file =
@"..\..\..\Cons oleApplication2 \bin\debug\Cons oleApplication2 .exe";
if ( !System.IO.File .Exists(file) )
{
Print("Unable to locate file {0}",file);
return;
}
Process p = new Process();
ProcessStartInf o psi = new ProcessStartInf o(file,"2");
p.StartInfo = psi;

IntPtr handle;
bool createdNew;
if ( !CreateManagedE vent(out handle,out createdNew) )
{
Print("Error creating named event.");
return;
}

if ( !createdNew )
{
Print("App2 already running. Press any key to exit...");
Console.ReadLin e();
return;
}
else
{
Console.WriteLi ne("Starting other app");
ManualResetEven t _evt = new ManualResetEven t(false);
_evt.Handle = handle;
_evt.Reset();
DateTime start = DateTime.Now;
p.Start();

Print("Waiting. ...");
_evt.WaitOne(Ti meSpan.FromSeco nds(15),false);
TimeSpan elapsed = DateTime.Now - start;
Print("Done waiting; it took {0} seconds...",ela psed.Seconds);
}
Print("All done");

}

/// <summary>
/// Creates a named event in the win32 space. This is a manual
/// reset event that is initially not signalled.
/// </summary>
/// <param name="handle"></param>
/// <param name="createdNe w">true if it created a new one, false if it
opened an existing one</param>
/// <returns>true if it succeeds, otherwise false</returns>
static bool CreateManagedEv ent(out IntPtr handle,out bool createdNew)
{
createdNew = false;
handle = CreateEvent(Int Ptr.Zero, true,false, "MyNamedEvent") ;
int error = Marshal.GetLast Win32Error();
if ( handle == IntPtr.Zero )
return false;
createdNew = (error != ERROR_ALREADY_E XISTS);
return true;
}

static void Print(string format,params object[] args)
{
string msg = string.Format(f ormat,args);
Trace.WriteLine (msg);
Console.WriteLi ne(msg);
}
}
}

in project 2
using System;
using System.Diagnost ics;
using System.Threadin g;
using System.Runtime. InteropServices ;

namespace ConsoleApplicat ion2
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class2
{
[DllImport("kern el32.dll", SetLastError=tr ue)]
static extern IntPtr CreateEvent(Int Ptr lpEventAttribut es, bool
bManualReset,
bool bInitialState, string lpName);

[DllImport("kern el32.dll")]
static extern bool SetEvent(IntPtr hEvent);

[DllImport("kern el32.dll")]
static extern bool ResetEvent(IntP tr hEvent);
[DllImport("kern el32.dll", SetLastError=tr ue)]
static extern int CloseHandle(Int Ptr hObject);

const int ERROR_ALREADY_E XISTS = 183;

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
IntPtr handle;
bool createdNew;
if ( !CreateManagedE vent(out handle,out createdNew) )
{
Print("Error creating named event.");
return;
}

if ( createdNew )
{
Print("App1 not running yet, exiting after a 10 second wait...");
Thread.Sleep( TimeSpan.FromSe conds(10) );
return;
}
Print("Sleeping for a few seconds...");
Thread.Sleep( TimeSpan.FromSe conds(2) );
Print("Done sleeping, setting event...");
ManualResetEven t _evt = new ManualResetEven t(false);
_evt.Handle = handle;
_evt.Set();
Print("Sleeping for 10 more seconds...");
Thread.Sleep( TimeSpan.FromSe conds(10) );
Print("Done");
}
/// <summary>
/// Creates a named event in the win32 space. This is a manual
/// reset event that is initially not signalled.
/// </summary>
/// <param name="handle"></param>
/// <param name="createdNe w">true if it created a new one, false if it
opened an existing one</param>
/// <returns>true if it succeeds, otherwise false</returns>
static bool CreateManagedEv ent(out IntPtr handle,out bool createdNew)
{
createdNew = false;
handle = CreateEvent(Int Ptr.Zero, true,false, "MyNamedEvent") ;
int error = Marshal.GetLast Win32Error();
if ( handle == IntPtr.Zero )
return false;
createdNew = (error != ERROR_ALREADY_E XISTS);
return true;
}

static void Print(string format,params object[] args)
{
string msg = string.Format(f ormat,args);
Trace.WriteLine (msg);
Console.WriteLi ne(msg);
}
}
}

"Chris B" <Ch****@discuss ions.microsoft. com> wrote in message
news:B6******** *************** ***********@mic rosoft.com...
I have the following situation:

Process 1 creates Process 2 (using Process.Start(s tartInfo)
Process 1 needs to wait until Process 2 is initialized before Process 1 can continue to execute Both processes are non-GUI processes.

The problem that I am running into is that the Process.Start(s tartInfo) returns immediately to Process 1. Therefore, process 1 does not wait on its
own for Process 2 to initialize.
Process 2 can take a few seconds to intialize. Process 1 needs to halt its execution until Process 2 is initialized. How can process 1 and 2
signal eachother to accomplish what I'm after?
In process 1 I tried using a Mutex:

Process process = Process.Start(s tartInfo);

if (process != null)
{
Mutex m = new Mutex(false, "Mutex");
m.WaitOne();
...
}

Process 2:

Main...
{
bool mutexWasCreated = false;
Mutex m = new Mutex(true, "Mutex", out mutexWasCreated );
if (mutexWasCreate d)
{
...
m.ReleaseMutex( );
}
}

this doesn't come close to working because process 1 gets the mutex before process 2 can acquire the lock. What I need is the ability to have process
1 wait on a mutex, have process 2 acquire the mutex lock, do its
initialization, then release the mutex, then process 1 resumes execution.
I have gotten the above to work in C++ using the CreateEvent API. Process 1 creates an unsignaled event, process 1 launches process 2, process 1 waits
on the event, process 2 does its thing, process 2 signals the event, process
1 continues.
How can I do this in C#?

Thanks!

Nov 16 '05 #2
Try using the following classes instead

AutoResetEvent
ManualResetEven t

Andy Cooper

"Chris B" wrote:
I have the following situation:

Process 1 creates Process 2 (using Process.Start(s tartInfo)
Process 1 needs to wait until Process 2 is initialized before Process 1 can continue to execute
Both processes are non-GUI processes.

The problem that I am running into is that the Process.Start(s tartInfo) returns immediately to Process 1. Therefore, process 1 does not wait on its own for Process 2 to initialize.

Process 2 can take a few seconds to intialize. Process 1 needs to halt its execution until Process 2 is initialized. How can process 1 and 2 signal eachother to accomplish what I'm after?

In process 1 I tried using a Mutex:

Process process = Process.Start(s tartInfo);

if (process != null)
{
Mutex m = new Mutex(false, "Mutex");
m.WaitOne();
...
}

Process 2:

Main...
{
bool mutexWasCreated = false;
Mutex m = new Mutex(true, "Mutex", out mutexWasCreated );
if (mutexWasCreate d)
{
...
m.ReleaseMutex( );
}
}

this doesn't come close to working because process 1 gets the mutex before process 2 can acquire the lock. What I need is the ability to have process 1 wait on a mutex, have process 2 acquire the mutex lock, do its initialization, then release the mutex, then process 1 resumes execution.

I have gotten the above to work in C++ using the CreateEvent API. Process 1 creates an unsignaled event, process 1 launches process 2, process 1 waits on the event, process 2 does its thing, process 2 signals the event, process 1 continues.

How can I do this in C#?

Thanks!

Nov 16 '05 #3
Those classes do not support named events which means they cannot be used
between processes.

"AKA COOPERMAN" <AK**********@d iscussions.micr osoft.com> wrote in message
news:DA******** *************** ***********@mic rosoft.com...
Try using the following classes instead

AutoResetEvent
ManualResetEven t

Andy Cooper

"Chris B" wrote:
I have the following situation:

Process 1 creates Process 2 (using Process.Start(s tartInfo)
Process 1 needs to wait until Process 2 is initialized before Process 1 can continue to execute Both processes are non-GUI processes.

The problem that I am running into is that the Process.Start(s tartInfo) returns immediately to Process 1. Therefore, process 1 does not wait on its
own for Process 2 to initialize.
Process 2 can take a few seconds to intialize. Process 1 needs to halt its execution until Process 2 is initialized. How can process 1 and 2
signal eachother to accomplish what I'm after?
In process 1 I tried using a Mutex:

Process process = Process.Start(s tartInfo);

if (process != null)
{
Mutex m = new Mutex(false, "Mutex");
m.WaitOne();
...
}

Process 2:

Main...
{
bool mutexWasCreated = false;
Mutex m = new Mutex(true, "Mutex", out mutexWasCreated );
if (mutexWasCreate d)
{
...
m.ReleaseMutex( );
}
}

this doesn't come close to working because process 1 gets the mutex before process 2 can acquire the lock. What I need is the ability to have
process 1 wait on a mutex, have process 2 acquire the mutex lock, do its
initialization, then release the mutex, then process 1 resumes execution.
I have gotten the above to work in C++ using the CreateEvent API. Process 1 creates an unsignaled event, process 1 launches process 2, process
1 waits on the event, process 2 does its thing, process 2 signals the event,
process 1 continues.
How can I do this in C#?

Thanks!

Nov 16 '05 #4
Try looking into System.Threadin g.Mutex. As far as Im aware they
implement named events that do work across processes.

HTH
Kieran

"David Levine" <no************ ****@wi.rr.com> wrote in message news:<#L******* *******@TK2MSFT NGP10.phx.gbl>. ..
Those classes do not support named events which means they cannot be used
between processes.

"AKA COOPERMAN" <AK**********@d iscussions.micr osoft.com> wrote in message
news:DA******** *************** ***********@mic rosoft.com...
Try using the following classes instead

AutoResetEvent
ManualResetEven t

Andy Cooper

"Chris B" wrote:
I have the following situation:

Process 1 creates Process 2 (using Process.Start(s tartInfo)
Process 1 needs to wait until Process 2 is initialized before Process 1 can continue to execute Both processes are non-GUI processes.

The problem that I am running into is that the Process.Start(s tartInfo) returns immediately to Process 1. Therefore, process 1 does not wait on its
own for Process 2 to initialize.
Process 2 can take a few seconds to intialize. Process 1 needs to halt its execution until Process 2 is initialized. How can process 1 and 2
signal eachother to accomplish what I'm after?
In process 1 I tried using a Mutex:

Process process = Process.Start(s tartInfo);

if (process != null)
{
Mutex m = new Mutex(false, "Mutex");
m.WaitOne();
...
}

Process 2:

Main...
{
bool mutexWasCreated = false;
Mutex m = new Mutex(true, "Mutex", out mutexWasCreated );
if (mutexWasCreate d)
{
...
m.ReleaseMutex( );
}
}

this doesn't come close to working because process 1 gets the mutex before process 2 can acquire the lock. What I need is the ability to have
process 1 wait on a mutex, have process 2 acquire the mutex lock, do its
initialization, then release the mutex, then process 1 resumes execution.
I have gotten the above to work in C++ using the CreateEvent API. Process 1 creates an unsignaled event, process 1 launches process 2, process
1 waits on the event, process 2 does its thing, process 2 signals the event,
process 1 continues.
How can I do this in C#?

Thanks!

Nov 16 '05 #5
To my knowledge mutexes are named but events are not. Do you have
information that contradicts this?

"Kieran Benton" <ki**********@f astmail.fm> wrote in message
news:65******** *************** ***@posting.goo gle.com...
Try looking into System.Threadin g.Mutex. As far as Im aware they
implement named events that do work across processes.

HTH
Kieran

"David Levine" <no************ ****@wi.rr.com> wrote in message

news:<#L******* *******@TK2MSFT NGP10.phx.gbl>. ..
Those classes do not support named events which means they cannot be used between processes.

"AKA COOPERMAN" <AK**********@d iscussions.micr osoft.com> wrote in message news:DA******** *************** ***********@mic rosoft.com...
Try using the following classes instead

AutoResetEvent
ManualResetEven t

Andy Cooper

"Chris B" wrote:

> I have the following situation:
>
> Process 1 creates Process 2 (using Process.Start(s tartInfo)
> Process 1 needs to wait until Process 2 is initialized before Process 1
can continue to execute
> Both processes are non-GUI processes.
>
> The problem that I am running into is that the
Process.Start(s tartInfo) returns immediately to Process 1. Therefore, process 1 does not wait on its own for Process 2 to initialize.
>
> Process 2 can take a few seconds to intialize. Process 1 needs to
halt its execution until Process 2 is initialized. How can process 1 and 2
signal eachother to accomplish what I'm after?
>
> In process 1 I tried using a Mutex:
>
> Process process = Process.Start(s tartInfo);
>
> if (process != null)
> {
> Mutex m = new Mutex(false, "Mutex");
> m.WaitOne();
> ...
> }
>
> Process 2:
>
> Main...
> {
> bool mutexWasCreated = false;
> Mutex m = new Mutex(true, "Mutex", out mutexWasCreated );
> if (mutexWasCreate d)
> {
> ...
> m.ReleaseMutex( );
> }
> }
>
> this doesn't come close to working because process 1 gets the mutex

before process 2 can acquire the lock. What I need is the ability to have process 1 wait on a mutex, have process 2 acquire the mutex lock, do its
initialization, then release the mutex, then process 1 resumes execution. >
> I have gotten the above to work in C++ using the CreateEvent API.

Process 1 creates an unsignaled event, process 1 launches process 2,

process 1 waits on the event, process 2 does its thing, process 2 signals the event, process 1 continues.
>
> How can I do this in C#?
>
> Thanks!
>
>
>

Nov 16 '05 #6

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

Similar topics

3
2536
by: Keith Veleba | last post by:
Hello to all fellow c.l.p'ers! Long-time listener, first-time caller. Background: I'm working on a project where I have to do some serious multithreading. I've worked up a decorator in Python 2.3.4 to implement the lock semantics required for specific functions I want to synchronize:
0
1985
by: SQLServer007 | last post by:
25 more days until the "get it free" promotion runs out for xSQL Object (you can get it from http://www.x-sql.com) Here are just some of the great features packed in the product: - Compare SQL Server objects (databases, tables, views, stored procedures, user defined data functions etc.) accross servers. - view and print dependencies; - generate color coded scripts for any object in the database or many of them at once (many configurable...
1
1562
by: Phil Matish, MCSE | last post by:
I have an Access database that I use frequently. Often, I take it to a home PC, or laptop to work on at night. The next day, I overwrite the old one with the one I have been working on. The only problem is - during this time, others may want to add records at the office. This causes an obvious data loss problem if I overwrite their edition of the database. Is there a way to synchronize the database? If someone made additions at...
1
4151
by: Jeff Smith | last post by:
Hi This is a repost due to no responses Here's a problem I've encountered with Access 2003 which has got me to redesign how I get the row source in a second combo box using the first combo box as a filter. In Access 2002 and earlier the row source for the second combo was "SELECT Field1, Field2 etc, FROM MyTable WHERE Field3 =
5
2345
by: suslikovich | last post by:
Hi everyone, I have a problem synchronizing two list boxes on a form. I want to display information in the second box based on the selection in the first box. First box (List0)lists all company names from table that lists quotes. I diplay a company only once even if it is listed more that one time. The second box (List4)should display quotes for a selected company (one or more.) Here is what I have for AfterUpdate in the first box:
2
3720
by: Christopher D. Wiederspan | last post by:
We are getting ready to move an ASP.NET application off of a single development machine and onto a "webfarm". Basically our webfarm is a bunch of identical servers with the load-balancing provided by a network appliance. What I'm wondering is what is the best way to keep the ASP.NET (.aspx and .dll) files synchronized across all of the servers in the farm. Our ASP.NET application is very simple - we could just copy the content to all of...
7
1129
by: Alphonse Giambrone | last post by:
I am not sure if these are the correct groups to post this, so please redirect me if there are better ones. Client has a SQL Server db of organizations and member info that is in pretty much constant use at his location. He would like to make the maintenance of adding/editing member info available on the web. Since the data contains personal info the web app (built in ASP.NET) will use SSL. The unique identifier for a member is the...
4
1784
by: Chris Ochs | last post by:
We have a number of tables in a CRM that is written in MS access that I need to be able to provide a web interface to. I can export the tables just fine using pgadmin II, but I cant' think of a clean way to import them from postgresql back to access. Synchronizing only needs to happen once a day at the most. I was also thinking of using the MS access forms with access tables that are just odbc links to the postgresql database. Does...
1
1200
by: Bostonasian | last post by:
Here's challenging task I got. Is it possible to synchronizing to smtp server by utilizing php and sending email info(sender,rcpt, message) to MySql?
0
9656
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
9499
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,...
0
10374
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10177
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...
0
8995
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...
1
7519
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
6750
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();...
2
3677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2898
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.