|
OK. Here is what I have:
<br />
public class LockClass<br />
{<br />
public static readonly object LOCK_OBJECT = new object();<br />
}<br />
<\code><br />
In another class in the same namespace:<br />
<code><br />
public bool commandUnForceAll()<br />
{<br />
lock(LockClass.LOCK_OBJECT)<br />
{<br />
<br />
if ( OpenPort() == false )<br />
Give_Status = false;<br />
else<br />
{<br />
Give_Status = false;<br />
byteToSend = new byte[3];<br />
byteToSend[0] = CMDUNFORCEALL;<br />
sum_xmit_bfr (0);<br />
if (sendAndGetData(3, 5))<br />
Give_Status = true;<br />
else<br />
{<br />
MessageBox.Show("Command Fail received from PCC-III to CommandUnForceAll()");<br />
Give_Status = false;<br />
}<br />
<br />
}<br />
}<br />
return Give_Status;<br />
}<br />
<br />
<br />
public bool commandForceBlockOutput(int block, int blockOutput)<br />
{<br />
lock(LockClass.LOCK_OBJECT)<br />
{<br />
<br />
if ( block < 3)<br />
{<br />
MessageBox.Show(this, "Cannot Force blocks 0-3");<br />
return false;<br />
}<br />
if ( OpenPort() == false )<br />
Give_Status = false;<br />
else<br />
{<br />
Give_Status = false;<br />
byteToSend = new byte[6];<br />
byteToSend[0] = CMDFORCEBLOCKOUTPUT;<br />
byteToSend[1] = Convert.ToByte(block);<br />
byteToSend[2] = Convert.ToByte(((blockOutput & -256) / 256) & 255);<br />
byteToSend[3] = Convert.ToByte(blockOutput & 255);<br />
sum_xmit_bfr(3);<br />
if (sendAndGetData(6,5))<br />
Give_Status = true;<br />
else<br />
{<br />
MessageBox.Show("Command Fail received from PCC-III to CommandForceBlockOutput(" + block + ")");<br />
Give_Status = false;<br />
}<br />
}<br />
}<br />
return Give_Status;<br />
}<br />
I am at a lost as to why this will not work. I am so very greatful for all your help.
*****************
"We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW
|
|
|
|
|
There is one thing that annoys me , and that is your use of a member variable as a return value. When doing that, you take on the burden to be sure that access to that variable is synchronized too.
It's just a little thing, but add more of that, and you'll soon end up in a situation where you can't figure out why variable x suddenly changes its value.
If you have to use a member variable, be sure to declare it volatile. This ensures that the system doesn't use a cached value for performance reasons, but actually reads the value from the object heap.
"God doesn't play dice" - Albert Einstein
"God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr
|
|
|
|
|
You are right. I will change that to a local variable. The other thing that bothers me about the code (this is not my code... I just get to troubleshoot/fix it) is this use of byteToSend as a member array. The 10 different functions reinitialize the array to the size needed then call sendAndGetData() which actually writes to a controller via the serial port. Instead of passing these values to sendAndGetData, it is a member variable. I have not figured out the best way around this.
But that is another story.
*****************
"We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW
|
|
|
|
|
I didn't see it before, but there is only on condition I can think of that would give this output (considered that there really isn't a typo).
public bool function1()
{
Mutex mutex = new Mutex(false, "MyMutex");
mutex.WaitOne();
Console.WriteLine("mutex entered");
<span style='color: red; font-weight: bolder;'>
</span>
Console.WriteLine("mutex exiteded");
mutex.ReleaseMutex();
return Give_Status;
}
"God doesn't play dice" - Albert Einstein
"God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr
|
|
|
|
|
To combat this, I wrapped everything into a try catch block. No exceptions thrown. I have changed everything over to the Lock method you suggested. I copied and pasted into the functions and verified no typos.
I am at a loss. Thanks for your help. I could post more code if you think it would help.
*****************
"We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW
|
|
|
|
|
There are some things that you can rely on:
1. Only one thread will have access to code inside the lock block.
2. If you still get output like this:
entered lock block
exiting lock block
entered lock block
entered lock block
from code like this:
public void Foo()
{
lock(lockObject)
{
Console.WriteLine("entered lock block");
Console.WriteLine("exiting lock block");
}
}
Then // Some code must have thrown an exception which was caught and ignored, or logged somewhere else than std output, in the method that invoked Foo() . The only alternative, is that the first WriteLine invocation is placed outside the lock statement.
"God doesn't play dice" - Albert Einstein
"God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr
|
|
|
|
|
From MSDN:
"While a mutual-exclusion lock is held, code executing in the same execution thread can also obtain and release the lock. However, code executing in other threads is blocked from obtaining the lock until the lock is released."
This makes it sound like this will only work in multiple threads. A for loop is one thread... is it not.
Also,
There are two functions being called. Both have to work off the same lock. I tried it with one and it works. I apologize for the confussion. Fromt he original post, I need both functions to work off the same lock. This is what is not working. I can poll the one function (just did 100 times in a row) and it worked fine. when I poll two functions it fails.:
for(int i =1; i < 5; i++)
{
lockedFunction1()
lockedFunction2()
}
What is happening then is this output:
Function1 entered
Function1 exited
Function2 entered
Function1 entered
Function1 exited
Function2 exited (but with an error because value are not right because of mixup.
*****************
"We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW
|
|
|
|
|
My point is if there were an exception, we would never see the second function eventually exit.
Sorry that was not very clear.
*****************
"We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW
|
|
|
|
|
It's the second method call that's the problem. No mutex, monitor or lock statement can help you here as they are all concerned about threading.
But the output clearly says that you're running multithreaded. The lockedFunction2() invocation will not execute before lockedFunction1() is finished. To get the output you display, lockedFunction1(), lockedFunction2() or both must start another thread that outputs the text.
To test for this you could make this change to the output routine:
Console.WriteLine("function 1 entered in thread: " + System.Threading.Thread.CurrentThread.GetHashCode() );
if the hashcode differs in the output, then it's another thread. If it doesn't, then call an Exorcist
"God doesn't play dice" - Albert Einstein
"God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr
|
|
|
|
|
Know any good ones
entered commandSetBlockParameter in thread: 20
Exited commandSetBlockParameter in thread: 20
entered queryBlockParameter in thread: 20
entered commandSetBlockParameter in thread: 20
Exited commandSetBlockParameter in thread: 20
entered queryBlockParameter in thread: 20
entered commandSetBlockParameter in thread: 20
Exited commandSetBlockParameter in thread: 20
entered queryBlockParameter in thread: 20
Exited queryBlockParameter in thread: 20
Exited queryBlockParameter in thread: 20
That said, Let me add another issue. This is in a timer loop. The timer was ticking before the last passthrough finished. I can disable the timer until the loop completes than reenable it. This may be the only way to fix this.
However, The same problem happens elsewhere when I subscribe to an event and I end up writing two values. I will have to fix this and do more testing. Please do not give up on me. You have been a HUGE help. If I respond in a day, will you be here, or should I start a new thread?
Thanks so much...
Dwayne
*****************
"We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW
|
|
|
|
|
ok. I have updated the rest of the code and am able to stop it from happening in the timer by disabling it and reenabling it after the loop completes. The same problem still applies to when I subscribe to an event, this launches a new set of code (still in the same thread according to the output) that runs and overlaps.
For instance... the original description of two userControls each calling the same communications function. When the user selects the second control it send a stop message to the first control, but that does not stop the form from continuing through it's timer poll. It is in these transitions that the problem still happens.
-Dwayne
*****************
"We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW
|
|
|
|
|
I'm baffled. I can't imagine how you can possibly get such a result. Look at this, ugly, code:
using System;
using System.Threading;
using System.IO;
namespace ConsoleTestApp
{
public class MyClass
{
private Timer timer;
public static void Main(string[] args)
{
MyClass myClass = new MyClass();
using (FileStream fileStream = File.OpenWrite(@"C:\test.txt"))
{
using (StreamWriter sw = new StreamWriter(fileStream))
{
Console.SetOut(sw);
myClass.Start();
Thread.Sleep(10000);
myClass.Stop();
Thread.Sleep(1000);
}
}
}
public void Start()
{
timer = new Timer( new TimerCallback(MyTimerCallback), null, 0, 500 );
}
public void Stop()
{
timer.Dispose();
}
private void MyTimerCallback(object state)
{
for (int i = 0; i < 5; i++)
{
Foo();
}
}
private void Foo()
{
lock (this)
{
Console.WriteLine("Entered lock block in thread " + Thread.CurrentThread.GetHashCode());
Thread.Sleep(100);
Console.WriteLine("Leaving lock block in thread " + Thread.CurrentThread.GetHashCode());
}
}
}
}
It doesn't produce the outcome you get. Does your code look something like this?
"God doesn't play dice" - Albert Einstein
"God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr
|
|
|
|
|
Not really.
It would be more like:
using System;
using System.Threading;
using System.IO;
namespace ConsoleTestApp
{
public class MyClass
{
private Timer timer;
public static void Main(string[] args)
{
MyClass myClass = new MyClass();
timer.Interval=100;
timer.Enabled=true;
timer.Tick += new System.EventHandler(this.timer_Tick);
}
public void timer_Tick()
{
Foo1();
Foo2();
}
private void Foo1()
{
lock(LockClass.LOCK_OBJECT)
{
Console.WriteLine("Entered lock block in thread " + Thread.CurrentThread.GetHashCode());
Thread.Sleep(100);
Console.WriteLine("Leaving lock block in thread " + Thread.CurrentThread.GetHashCode());
}
}
private void Foo2()
{
lock(LockClass.LOCK_OBJECT)
{
Console.WriteLine("Entered lock block in thread " + Thread.CurrentThread.GetHashCode());
Thread.Sleep(200);
Console.WriteLine("Leaving lock block in thread " + Thread.CurrentThread.GetHashCode());
}
}
}
public class LockClass
{
public static readonly object LOCK_OBJECT = new object();
}
}
This was typed so my syntax may not be exact. There is also no start and stop events. this is mainly to let you get the idea.
As you can see it takes more time for the Foos to run that it takes for the timer to start the next tick. so the timer ticks and foo1 is started again while foo2 is still running.
So instead of this... I am putting the following in the Timer code:
public void timer_Tick()
{
try
{
timer.enabled = false;
Foo1();
Foo2();
}
finally
{
timer.enabled = true;
}
}
It is a patch, but it works. I am uncertain of the TimerCallBack. I will spend tonight figuring out that. Perhaps I am not using the Timer properly.
I must admit, I had/have little experience with the timers.
The other problem is when I subscribe to an event:
using System;
using System.Threading;
using System.IO;
namespace ConsoleTestApp
{
public class MyClass
{
private Timer timer;
private bool doStop1;
private bool doStop2;
private Button RunFoo2;
public static void Main(string[] args)
{
MyClass myClass = new MyClass();
timer1.Interval=100;
timer1.Enabled=true;
timer1.Tick += new System.EventHandler(this.timer_Tick);
timer2.Interval=100;
timer2.Enabled=false;
timer2.Tick += new System.EventHandler(this.timer_Tick);
RunFoo2.Click += new System.EventHandler(this.RunFoo2_Click);
}
public void RunFoo2_Click()
{
doStop1 = true;
timer2.enabled = true;
}
public void timer1_Tick()
{
try
{
timer1.enabled = false;
Foo1();
Foo2();
}
finally
{
if(!doStop1)
{
timer1.enabled = true;
}
}
}
public void timer2_Tick()
{
try
{
timer2.enabled = false;
Foo1();
Foo2();
}
finally
{
if(!doStop2)
{
timer2.enabled = true;
}
}
}
private void Foo1()
{
lock(LockClass.LOCK_OBJECT)
{
Console.WriteLine("Entered lock block in thread " + Thread.CurrentThread.GetHashCode());
Thread.Sleep(100);
Console.WriteLine("Leaving lock block in thread " + Thread.CurrentThread.GetHashCode());
}
}
private void Foo2()
{
lock(LockClass.LOCK_OBJECT)
{
Console.WriteLine("Entered lock block in thread " + Thread.CurrentThread.GetHashCode());
Thread.Sleep(200);
Console.WriteLine("Leaving lock block in thread " + Thread.CurrentThread.GetHashCode());
}
}
}
public class LockClass
{
public static readonly object LOCK_OBJECT = new object();
}
}
Thanks again.
-Dwayne
*****************
"We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW
|
|
|
|
|
hello friends
Reading c# books take a lot of my time
please can somebody give me a site where i can download
free C# videos
|
|
|
|
|
|
Im in the process of learning C#, and so far, I'm loving it. I've found a way to make calls to some old "C" DLLs, but I have a few questions regarding types.
[DllImport("MYDLL.DLL")]
public static extern ulong GetSerialNumbers ( byte f1, byte f2, byte NodeAddr, PIFS_CABLESER pserials, PUSHORT pcount );
I have a function in in MYDLL.DLL called GetSerialNumbers that returns an array of structures. I have no problems declaring functions with known types, but as soon as I add in a type that C# doesn't know, I'm stuck. I would like to take the data of these structures and copy them to a class I've created....
This is my C definition, would I have to make something equivalent that C# will understand?
typedef struct SerialInfoMD
{
byte ID[8];
byte something;
int new;
} IFS_CABLESER, *PIFS_CABLE_SER;
Anybody have any info to share?
Thanks!
Mike
|
|
|
|
|
Yes, as with the requirement of defining the function signature in C# you also have to supply a description of the structure as well. For the structure you provided the sig would be
[StructLayout(LayoutKind.Sequential)]
struct SerialInfoMD
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=8)]
public byte[] ID;
public byte Something;
public int New; // note the capitalization change. Syntax error otherwise.
}
Things can get tricky when marshalling data between managed and unmanaged code. For example, in your function signature you have the return type as ulong. Is the return type for the C function an unsigned long? Unsigned long is 32-bits on Win32 but is 64-bits on .NET so the appropriate return type in the C# method is uint if the return type on the C function is unsigned long. It gets even more murky when dealing with arrays. You might wanna check out information on data marshalling on MSDN. Try this URL for a start.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconInteropMarshaling.asp
|
|
|
|
|
hello, i need to change the scroll bar color for a ListView (i'm trying to make a flat gui). Can u plese help? Thx
|
|
|
|
|
You have to use css for that, and it will only work in Internet Explorer.
---
b { font-weight: normal; }
|
|
|
|
|
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=2600&lngWId=10
Live Life King Size
Alomgir Miah
|
|
|
|
|
I need to create a Bitmap of a datagrid. Is there a way to do this?
|
|
|
|
|
VS.NET executes the code behind Propertys when you change them in the property grid in the designer. Is there anyway to modify the code such that it knows when it's being changed via the designer? There is some code in my get/set that has some unwanted side effects during design time.
|
|
|
|
|
|
Hi all.
I have a strange problem with Webservices:
In a webmethod I modify the value of a variable (string) inside an instance of a class that I created. When the webmethod returns, the change of the string is lost, and it returns to its initial value.
a concrete example
class MyClass {
private string s;
public string String {
get { return s; }
set { s = value; }
}
}
private MyClass data = new MyClass();
[WebMethod()]
public MyMethod(string s) {
data.String = s;
// Consume data.String -> correct value
}
private void otherMethod() {
// Consume data.String -> WRONG VALUE
}
The webservice calls MyMethod().
In a successive call to another webmethod, otherMethod() is called and the data.String value is wrong!!!
I tries to use methods Set() Get() instead of the public property but nothing changes.
Maybe I don't know an important thing???
Any help will be very ... HELPFUL!
|
|
|
|
|