C# why two same thread fire same method at same time? - c#

First of all my question is quite complicated (for me) and I try to explain.
I have a WPF application which is working with NFC tags. Couple days ago this code was worked properly but now somethings messed up.
First I have a method which is reading data from NFC tag like this:
private void NFCCard_OnCardInserted()
{
CheckCard();
}
private bool CheckCard()
{
try
{
lock (_object)
{
NFCCard.Connect(CardReader, SHARE.Shared, PROTOCOL.T0orT1);
APDUPlayer player = new APDUPlayer(ApduListFile, NFCCard);
if (nfcFunction.NFCLogin(player))
{
string TempCompanyID = "";
//--Read data
}
DateTime cartOpenedDate = Convert.ToDateTime(OpenedDate);
if (CartNo == "" || CompanyID.ToString() == "" || Convert.ToInt32(limit) <= 0 || isactive == "False" || cartOpenedDate.ToShortDateString() != DateTime.Today.ToShortDateString() || CartType == "Staff")
{
Dispatcher.BeginInvoke(new Action(delegate
{
ShowCardNo(txtCardNo, "Geçersiz Kart!");
}));
}
else
{
//-- Some internal code
}
}
}
catch (Exception exc)
{
StationSession.WriteLog("write log bla bla", exc);
}
}
Now is the funny thing when I check the threads windows of VS two same thread try to run NFCCard_OnCardInserted() method at same time.
For this reason I put lock state but the problem is this method firing two times. And its make big trouble for me because the card transaction time is being double right now (almost 3 second for some transaction. I cannot explain to people you will wait with cart at cart reader like this :/ ). By the way I check whole page for this method reference, just this code should use this method.
NFCCard.OnCardInserted += new CardInsertedEventHandler(NFCCard_OnCardInserted);
So how can I fix this problem without workaround. Because I have several page and method which is using NFC cart thread. I need to find clear way for this problem. Thanks.

Related

Different functions different delays c#

I'm making a simple c# game similar to snake, and I have two moving aspects. I have a method to move both of them, however I want them to both move at different speeds. Here's a cut down version of the method I have now.
private async void mover()
{
while (GlobalVar.Status == "alive")
{
if (GlobalVar.Direction == "up")
{
try { moveupp(GlobalVar.Row, GlobalVar.Column, "player"); }
catch (System.IndexOutOfRangeException) { died(); }
}
if (GlobalVar.OppDirection == "up")
{
try { moveupp(GlobalVar.Row, GlobalVar.Column, "opp1"); }
catch (System.IndexOutOfRangeException) { died(); }
}
await Task.Delay(500);
}
}
Here, in the first IF statement, my character (player) is moving up, and in the second IF statement, the opponent (opp1) is moving up. These are working in sync with a 500 millisecond delay in between with the delay "await Task.Delay(500);".
My question is, is there anyway they can both run together, with different delays in between? So the opp1 can move faster than the player?
Many thanks in advance!
I would use two different timers instead of delaying tasks. Also I would not use exceptions to control program flow:
private PlayerTimer_Tick(object sender, EventArgs e)
{
if (GlobalVar.Status != "alive")
return; // you can also stop timer in this case
if (GlobalVar.Direction == "up")
{
if (GlobalVar.Column == 0)
died();
else
moveupp(GlobalVar.Row, GlobalVar.Column, "player");
}
}
Also create timer for opp1 and set different intervals for these timers - 500 for player and another value for opp1.

How do I get these if statements to play nicely in c#

I've modified my code to the point where it will execute, but it's linked to a timer, and will attempt to execute over and over till the timed condition is lost. I tried putting a "lock" on the system with a variable I named "intLimiter", to force the sequence to stop after one execution, but the lock doesn't seem to be working.
if (DateTime.Now.Hour == intAlarmHour && DateTime.Now.Minute == intAlarmMinute)
{
if (intLimiter == 1)
{
intLimiter = 2;
if (radTG.Checked)
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(Properties.Resources.Celldweller___Tough_Guy);
sound.Play();
}
...
}
}
As of what I understand from your question, you want to separate the if statements to work all at the same time...
What you can do is create new 'Threads' for each statement which would make you able to run all of then at once...
For thread, make sure you include the namespace System.Threading.
using System.Threading;
Now what you should do with your code:
...
if (DateTime.Now.Hour == intAlarmHour && DateTime.Now.Minute == intAlarmMinute)
{
if (radTG.Checked == true)
{
Thread radTG = new Thread(radTGChecked);
radTG.Start();
}
...
}
...
public void radTGChecked() {
SoundPlayer sound = new SoundPlayer(Properties.Resources.Celldweller);
sound.PlaySync();
}
Do this to all the if statements following, and they will all run together, each on a thread...
Forgive me if that was not the answer of your question, but the title corresponding to the content does seem a little blurry to me...
But if it did, here's an article that will help you understand Multi-Threading.

Strange in ShakeGesture Library on Windows Phone Application

i've a problem with windows phone shakegesture library.
I build an application which its shaking the sound will go out and its work nicely but strange bug make me confused. I've two page of it. This is my seperated code :
void Instance_ShakeGesture1(object sender, ShakeGestureEventArgs e)
{
Stream stream = TitleContainer.OpenStream("Sounds/C.wav");
effect = SoundEffect.FromStream(stream);
effectInstance = effect.CreateInstance();
if (effectInstance.State != SoundState.Playing || effectInstance == null)
{
FrameworkDispatcher.Update();
effectInstance.Play();
}
else if (effectInstance.State == SoundState.Playing || effectInstance != null)
{
effectInstance.Stop();
}
}
void Instance_ShakeGesture2(object sender, ShakeGestureEventArgs e)
{
Stream stream = TitleContainer.OpenStream("Sounds/D.wav");
effect = SoundEffect.FromStream(stream);
effectInstance = effect.CreateInstance();
FrameworkDispatcher.Update();
if (effectInstance.State == SoundState.Stopped || effectInstance == null)
{
effectInstance.Play();
}
else if (effectInstance.State == SoundState.Playing || effectInstance != null)
{
effectInstance.Stop();
}
}
Instance_ShakeGesture1 is my procedure to play a music when its shaking in Page 1 and Instance_ShakeGesture2 in Page 2.
Strange bug was come when its shaking, if i shake page 1 Instance_ShakeGesture1 will executed after that I try move to page 2 and i shake it will execute Instance_ShakeGesture1 first and than Instance_ShakeGesture2.
The Problem was come same when i try to shake Page 2 first and than Page 1, Instance_ShakeGesture2 will execute first and Instance_ShakeGesture2 in the second.
I know this bug when i use breakpoint.
Anyone know how to solve this problem? Thanks before :)
Possibly the event Instance_ShakeGesture1 is still active when you navigate to the second page. try
Instance.ShakeEvent -= new EventHandler(Instance_ShakeGesture1);
inside the Instance_ShakeGesture1 method.
try this, it worked for me,
protected override void OnBackKeyPress(CancelEventArgs e)
{
e.Cancel = false;
ShakeGesturesHelper.Instance.ShakeGesture -= new EventHandler<ShakeGestureEventArgs>(Instance_ShakeGesture1);
}
Because you should delete the events when you leaving first page. So you can clean hakeGestureEventArgs when back key button is pressed.
Okay my bad. Didn't know that you needed it to work multiple times.
Try this and let me know if it works good:
Write the same line of code that you've added, inside the OnNavigatedFrom method and delete it from your current method('Instance_ShakeGesture2')

Error Creating window handle

I've written a client-server c# app and let it run all night , and when i wanted to see if it was still working i've found an error on the server . unfortunately the app is to big to paste in some code, but i get an error at
Application.Run(form1)
in the program.cs that says
The first two messageboxes can be ignored (from left to right ) because they are supposed to show , but the other
delegate buton couldn't be executed
comes from this code ánd mai have a part in this error(this code is in form1.cs) :
public void setButonState(inout_buton b, bool t, int q,int contor)
{
try
{
if (b.InvokeRequired)
{
Callback d = new Callback(setButonState);
this.Invoke(d, new object[] { b, t, q, contor });
}
else
{
b.Enabled = t;
if (q == 0) b.setBackgroundGrey();
if (q == 1) b.setBackgroundGreen();
if (q == 2) b.setBackgroundRed();
if (q == 3) b.setBackgroundOrange();
b.setSecondaryLabel(contor);
}
}
catch { new ShowMessageBox("FORM1 : delegate buton couldn't be executed"); }
}
My question is : in what conditions does these errors show ?
Diagnose this with Taskmgr.exe, Processes tab. View + Select Columns and tick USER objects. Observe this value for your process while it runs. It should be steadily climbing. When it reaches 10,000 then your program will bomb with this exception.
This is caused by not calling Dispose() on controls that you remove from the Controls collection yourself, either by calling Remove() or Clear().
Sounds to me like your application is trying to access protected data. Keep in mind, when your system locks due to inactivity/logging off, your application will not be able to interact with certain aspects of the system. Such an example would be trying to grab the handle of a window or take a screen shot. These will both throw errors.
I was receiving this same error when calling a static classes method from within a foreach statement. The User Objects count continued to increase and was not released until the program ended or the error occurred.
I changed the static method into an instance method and the User Object stayed at 60.
//created and instance of the object
var oIP = new ImportProvider();
foreach(var patient in lstPatients)
{
var oP = PatientConversionProvider.GetPatient(oPatient.RecordId);
if(oP != null)
{
//referenced the instance member (changed from a static member)
if(oIP.ImportDataIntoSmartRx(oP))
{
successCount++;
lstMrNumber.Add(oPatient.MrNumber);
}
totalCount++;
...

Problem While receiving events from a thread

I'm Doing a project on FileTransfer in which i have a listview , i will get events from one of my class file for updating the percentage of the file sent so far,after receiving it i will place the percentage in my listview ,while doing that the listview got
a flickering effect how to avoid it.i used application.doevents() but it doesnt works. i have seen in torrents while updating the percent the list doesnt get flickered
how to achieve this .
void Sender_Progress(int CurrentValue, string Ip) // here im receiving Events
{
try
{
//if (CurrentValue == 1)
// UpdateTimer.Enabled = true;
//list_send.Items[CurrentValue].SubItems[4].Text = Ip.ToString();
//Application.DoEvents();
obj = new object[] {CurrentValue, Ip };
list_send.Invoke(new UpdateList(UpList), obj);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void UpList(int Val, string ind) // here im updating the listview
{
Application.DoEvents();
int index = 0;
index = Convert.ToInt32(ind);
index = index - 1;
list_send.Items[index].SubItems[4].Text = Val.ToString();
if (Val == 100)
{
list_send.Items[index].SubItems[2].Text = "Completed.";
//UpdateTimer.Enabled = false;
}
//Application.DoEvents();
}
Firstly, you don't need the DoEvents, since you are already correctly working on two threads. Remove that. After that, I expect the problem is simply doing too much too quickly. Is it possible to batch updates, and only send an update, say, every 20? 50? times? It isn't clear what the control is, but many have multiple-update modes; for example with ListView:
theList.BeginUpdate();
try {
// make multiple updates here...
} finally {
theList.EndUpdate();
}
I would then see about passing over a list of updates, say, every 20 times (unless each takes a considerable time) [note it must be a different list per Invoke, and you need to remember to send any remaining items at the end, too].
Use worker thread - it's available from the toolbox and has two events that are invoked in the main (UI) thread.
The Progress event can be used to signal the listbox that it need to refresh or that the task was completed.
i overcome the flickering effect succesfully,im getting events frequently ,i will get an integer everytime, i will store it in a variable and compare it with next variable received by the event if it matches i wont invoke the listview,otherwise i will invoke it.now the flickering goes away. thanks all.

Categories

Resources