c# event can enter to function twice in same time? [duplicate] - c#

This question already has answers here:
Is it necessary to synchronize .NET SerialPort writes/reads?
(2 answers)
Closed 5 years ago.
SerialPort s = new SerialPort("COM32");
public MainWindow()
{
InitializeComponent();
s.DataReceived += dataAction;
}
private void dataAction(object sender, SerialDataReceivedEventArgs e)
{
}
the function dataAction can be run on same time with 2 event?
or dataAction apply only when the last event finish?
I must to know that to know If i need to put lock on this function

Event will trigger everytime they are called. If they are called multiple times from multiple threads they will be triggered synchronously.
However, in your specific case, it seems you register to a specific element which seems to be monothreaded (can't be sure as I don't know SerialPort api)

Related

Can I call Win API functions from a WPF application [duplicate]

This question already has answers here:
How to Call Windows API [duplicate]
(2 answers)
how to set timer resolution from C# to 1 ms?
(2 answers)
Closed 2 years ago.
I have a WPF application that controls a robot arm. It's also a human-in-the-loop system. So I would like it to be as close to real time as possible. I am using a DispatcherTimer to generate a "tick" regularly to update the robot arm. Sort of like a poor mans Gameloop:
public partial class MainWindow : Window
{
DispatcherTimer Timer;
public MainWindow()
{
InitializeComponent();
Timer = new DispatcherTimer(DispatcherPriority.Send);
Timer.Interval = TimeSpan.FromMilliseconds(10);
Timer.Tick += new EventHandler(OnTick);
}
private void OnTick(object sender, EventArgs e)
{
//1.Read input devices
//2.Do calculations
//3.Move robot arm
}
}
To be as near to real time as possible, this tick has to be generated as fast as possible, but because of limitations in Windows, the line...
Timer.Interval = TimeSpan.FromMilliseconds(10);
...has no real effect for values under ~15. It is limited by the fact that Windows schedules the "sleeps" and "wakes" of threads in 15.6ms intervals as explained nicely by Bruce Dawson here.
But, as is also explained in this article, this default scheduling interval can be changed by calling timeBeginPeriod in timeapi.h
Can someone show or point me to an example how to call WinAPI functions, like timeBeginPeriod(10); from a WPF application?

Main thread Error in Unity [duplicate]

This question already has answers here:
Use Unity API from another Thread or call a function in the main Thread
(5 answers)
Closed 6 years ago.
I am using Unity 5.0.
I am trying to download some file using C# web client asynchronous.
File gets downloaded and DownloadDataCompleted events also gets fired.
Then I try to do some calculation but I get these error.
RandomRangeInt can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
Any solution to above problem or can anyone tell me how to run that calculation part on main thread
As requested code is here
private void DownloadXMLFromServer()
{
//first download the file from server
WebClient _maClient = new WebClient ();
_maClient.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs e)
{
File.WriteAllBytes("DownloadedXML.xml",e.Result);
DownloadImgOfApp();
};
_maClient.DownloadDataAsync (new Uri (instance.urlOf_XML));
}
public void DownloadImgOfApp()
{
int appNumber = UnityEngine.Random.Range (0, totalNumbOfAppsAvaialbeInXML);//these line throws error
string appName = "App" + (appNumber + 1);
string downloadImgLinkName = null;
string clickableLink = null; }
A lot of methods in Unity3D can be called just from the main thread. This means they can only be called in Start() Update() Awake() OnTriggerEnter(...) and so on. Unity will not let you call these methods from different threads (including asynchronous callbacks).
This makes sense for things like GameObject.Instatiate(...), but I cannot think of a reason why random could cause problems. But for some reason Unity is blocking calls anyway.
To solve your problem, you can create an instance of System.Random and generate your random numbers with it.
The only Problem I can see is that System.Random cant give you a float, just bytes, int or double.

How to convert Console application to winforms? [duplicate]

This question already has answers here:
How do I convert a .NET console application to a Winforms or WPF application
(2 answers)
Closed 8 years ago.
I want to do some changes here, I want to convert this application to winforms. And i want to store these output into a text file, How can I do it? please help
using System;
using System.Threading;
public static class Program
{
public static void Main()
{
// Create a Timer object that knows to call our TimerCallback
// method once every 2000 milliseconds.
Timer t = new Timer(TimerCallback, null, 0, 1000);
// Wait for the user to hit <Enter>
Console.ReadLine();
}
private static void TimerCallback(Object o)
{
// Display the date/time when this method got called.
Console.WriteLine(DateTime.Now);
// Force a garbage collection to occur for this demo.
GC.Collect();
}
}
Output of this application.
Source Stackoverflow
Go to application > and change is Application type to Winform and then point start up object at Sub Main
Right click on the solution and select "Add Reference"
Select System.Windows.Forms and hit OK

c# show hidden window of a process [duplicate]

This question already has answers here:
Run one instance of program
(2 answers)
Closed 9 years ago.
There is an option in my application to hide the window - form.hide(), and to put an notifyicon in the system tray, and when you click the notifyicon there will be a form.show().
If someone will try to run two instances of the app, I want
a. not to run the new instance
b. to show the window of the first instance
I already have a loop to check if a process with the same name exists.
and I can tell the new app not to run ( return in the program.cs before Application.run(new form()))
but I yet have to tell the first app to show its main window.
I have the process (of the first instance) , i can get its handle its id etc.
the question
How to show the window using it's process?
For the first part of the question, here is what you can do. Add this in the Main before you show your form. The benefit of this is that you don't check by process name (which might not be unique), but you create a mutex which is somehow "global".
using (Mutex applicationMutex = new Mutex(true, "SomeRandomTextHere", out mutexCreated))
{
if (!mutexCreated)
{
// Application is already running. Aborting..
return;
}
// Application.Run(..) goes here, plus other interesting stuff
}
For the second part of your question I would suggest the following:
Create a named event and set it initially to false. Then create a worker thread in your application that monitors this event. When it is signaled, Invoke your Show method from your main form.
Another approach is to search for the window handle of the main process and bring it to front. This article can give you ideas.
Bear in mind that doing a loop through all processes is not as efficient as using a mutex. If you don't care about speed, clean code and you just want this app to work then use this loop.. To me code is poetry.
Rewrote the code just for you this will give you exactly what you want. It will check for duplicates and focus the screen when a duplicate is opened.
EventWaitHandle ProgramOpen = new EventWaitHandle(false, EventResetMode.ManualReset, "ProgramOpen198472");
EventWaitHandle FocusProgram = new EventWaitHandle(false, EventResetMode.ManualReset, "FocusMyProgram198472");
private delegate void focusConfirmed(); Thread FocusCheck;
private void focus() { FocusProgram.WaitOne(); this.Invoke(new focusConfirmed(()=>{this.Show(); this.BringToFront();}));}
private void Form1_Load(object sender, EventArgs e)
{
if (ProgramOpen.WaitOne(0))
{
FocusProgram.Set();
this.Close();
}
ProgramOpen.Set();
}
private void HideButton_Click(object sender, EventArgs e)
{
this.Hide();
FocusProgram.Reset();
FocusCheck = new Thread(focus);
FocusCheck.Start();
}
private void showToolStripMenuItem_Click(object sender, EventArgs e)
{
FocusProgram.Set();
}

How to use FileSystemWatcher to check whether a file is locked by another process? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Wait until file is unlocked in .NET
I have many cases where a program must wait until a file is unlocked by another process (e.g file being copied) before it can be used again. A standard solution is to wait for it iterating in a loop using Thread.Sleep(). I don't consider that kind nice. I've read it's possible to do it with the FileSystemWatcher of .NET (I'm using C#). Can anyone illustrate it? Thanks a lot for your replies!
FileSystemWatcher as the name suggests ,lets you watch for any events that occur when you change,create,delete,rename a file or folder
You cannot use FileSystemWatcher to check if the file is locked..
FileSystemWatcher _watcher;
int _watcherEventFiredCounter;
_watcher = new FileSystemWatcher {
Path = #"C:\temp",
NotifyFilter = NotifyFilters.LastWrite,
Filter = "*.zip",
EnableRaisingEvents = true
};
_watcher.Changed += OnChanged;
private void OnChanged(object sender, FileSystemEventArgs e)
{
_watcherEventFiredCounter++;
// The event is fired two times: on start copying and on finish copying
if (_watcherEventFiredCounter == 2) {
Console.WriteLine("Copying is finished now!");
_watcherEventCounter = 0;
}
}
Now the question is how can come back to the calling thread?

Categories

Resources