Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I created a method that polls a database. If two instances of the exe are run, I wouldn't want both instances to be able to run the polling method simultaneously.
How might I best ensure the polling method is only ever active in one thread (regardless of which process owns the thread), and that if another thread calls it it will throw an exception?
I would use Mutex to avoid multiple access to the same recourses.
Here you have a brief piece of code to achieve this
Mutex mutex;
private void StartPolling()
{
mutex = new Mutex(true, "same_name_in_here", out bool createdNew);
if (!createdNew) { throw new Exception("Polling running in other process"); }
//now StartPolling can not be called from other processes
//polling stuff in here
}
private void StopPolling()
{
mutex?.Dispose();
mutex = null;
//now StartPolling can be called from other processes
//Stop any polling operation
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have multiple threads in my program, one of which is operating on an internal data structure. Due to some error, this thread quits leaving the data structure in an invalid state. How can other threads properly validate the state of data structure on later access? In general, how to handle such a scenario?
The best answer is to make sure that threads don't quit leaving the data structure invalid. Other than that, the only solution is something like:
In class:
bool m_data_valid = true; // Or possibly 'false' and set it true in constructor
In mutating thread:
m_data_valid = false;
... // Mutate structure
m_data_valid = true;
In other threads:
if (!m_data_valid)
fixup(); // Or whatever you were going to do.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
object c = new object();
lock(c)
{
}
Why should i pass object to lock keyword while synchronizing above code.If i pass also where will it be used.I know it is used for acquiring a lock on that object.but i wanted to know how can we acquire lock on object in depth.How does the thread release the lock on the object we pass in lock keyword.
lock statement is a syntactic sugar of using Monitor approach to thread synchronization. Monitor represents an exclusive lock on some resource, and in .NET a resource is an object.
Why you need to give an object reference to a Monitor? Well, because you want to synchronize the access to the whole object in a multi-threaded environment.
How does the thread release the lock on the object we pass in lock
keyword?
Think about lock as follows:
Monitor.Enter(obj);
try
{
// This would be the code inside the "lock" block
}
finally
{
if(Monitor.IsEntered(obj))
Monitor.Exit(obj); // <-- This is how a Monitor releases the lock
}
you don't need to restrict your locking to an Object object, you could lock a Dictionary object for example, to prevent other threads from adding or deleting from the collection.
or
if you don't want to use the lock keyword, you could use [MethodImpl(MethodImplOptions.Synchronized)]
eg.
[MethodImpl(MethodImplOptions.Synchronized)]
static void mySynchronisedTask()
{
//do things that i want to be synchronised
Console.WriteLine("before sync task");
Thread.Sleep(5000);
Console.WriteLine("after sync task");
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have an application, in which I'm sending a command to hardware controller, then controller responds back to that command. In this, I have a queue of commands and I send them one by one, now i want to send all commands synchronously, means when I receive first commands response then only I will send next command.
I have two methods, one for send commands and another for handling received commands.
This is called signaling and the simplest way to implement it is via ManualResetEvent.
if you call WaitOne on a ManualResetEvent object, the current thread gets blocked until another thread "signals" it to continue by calling Set on the same object:
var signal = new ManualResetEvent(false); // instantiate in "unsignaled" state
new Thread (() =>
{
Console.WriteLine("Sending command to hardware controller...");
// send your command
// ...
Console.WriteLine("Done.");
signal.Set(); // signal the waiting thread that it can continue.
}).Start();
Console.WriteLine("Waiting for hardware thread to do it's work...");
signal.WaitOne(); // block thread until we are signaled.
signal.Dispose();
Console.WriteLine("Got our signal! we can continue.");
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
private async void btnLoadFile_Click(object sender, EventArgs e)
{
if(AccountsFile.ShowDialog()==DialogResult.OK)
{
Accounts = File.ReadAllLines(AccountsFile.FileName);
foreach(string str in Accounts)
{
await LoadAccount(str);
}
}
}
I've ran into a problem, I know how Asynchronous programming works it will wait for the task to be complete but LoadAccount() will never complete because it calls a function with a never ending while loop so it will not reach the next string in Accounts.
I don't know where to start with this problem. Any solutions?
Instead of waiting for each account successively, you could wait for them collectively. This way, even if one of your accounts enters an infinite loop, the others could still proceed to load.
Accounts = File.ReadAllLines(AccountsFile.FileName);
Task completionTask = Task.WhenAll(Accounts.Select(LoadAccount));
You would typically want to store completionTask in a class variable. Subsequently, when you break out of the indefinite while loop within your LoadAccount calls (for example, by signalling cancellation via a polled CancellationToken), you can use this completionTask to wait for all your tasks to complete.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Does this method use plenty of my memory resources?
Private MyWorkerClass worker;
Private Thread myWorkerThread;
//private Thread myWorkerThread= new Thread(worker.doThisWork); // i cant do this, because i cant restart the thread when i construct it here.
public void IwantMyWorkDosomething(){
myWorkerThread= new Thread(worker.doThisWork);
myWorkerThread.start();
myWorkerThread.stopWorking(); // stop my worker class thread running;
}
public void main(){
this.IwantMyWorkDosomething();
this.IwantMyWorkDosomething();
this.IwantMyWorkDosomething();
this.IwantMyWorkDosomething();
this.IwantMyWorkDosomething();
}
my Code is working, but i am not sure whether it gonna crash my program if i run the method 1000 times.
Constructing a thread object is cheap. Also, re-constructing a new one is cheap. The garbage collector will free the unused resources, you just need to make sure you're not unnessecarilly keeping references to finished thread objects.
What could become a resource problem is only when you try to run thousands of threads at the same time. But even then, it's not the memory that will usually cause the bottleneck but the CPU and the task scheduler (i.e the tasks will start to run slower than exected).