Using lock( ) C# [closed] - c#

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 9 years ago.
Improve this question
Why is this lock not working?
CheckActivity is generated from Mouse/Keyboard Windows hook. Any hint how to make this lock to work?
private void CheckActivity(KeyboardMouseKey k)
{
lock(this)
{
if (_map)
{
_map = false;
if (openFileDialogSelectAudio.ShowDialog() == DialogResult.OK)
MapSound(k, openFileDialogSelectAudio.FileName);
}
else
{
///play
foreach (var m in _mappings.Where(m => m.Key.Equals(k)))
m.Value.Play();
}
UpdateGui();
}
}

You are using lock(this).
If Check Activity is called on different objects, lock(this) will not prevent for making sure that only one thread is executing CheckActivity (which appears to be the purpose of the lock)
Use lock on static object to make it work.
Example:
private static readonly object lockObj = new object();
...
lock(lockObj)
{
....
}

Related

How to access my running code Thread from a GUI Textbox. C# Forms [closed]

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 4 years ago.
Improve this question
I am trying to access a method, and a variable in that method, that is also in a separate thread from a GUI Textbox in Windows Forms.
Every other question people have is how to go the other way by accessing the GUI from a separate thread that's the opposite of what I'm trying to do.
public ClientWindow()
{
InitializeComponent();
var ItemThread = new Thread(new ThreadStart(ItemRun));
ItemThread.Start();
}
public void ItemRun()
{ //..
}
public void Return(object sender, KeyEventArgs e)
{ //need to access a variable in ItemRun() from here
}
Thanks for any answers.
You just need to make your Variable/s Global, also if you need thread safety you need use some sort of locking mechanism
// create global variable
private volatile int somevar;
// create a sync object to lock
private int _sync = new object();
...
public void ItemRun()
{
// make sure you lock it
// if there might be race conditions or you need thread safety
lock(_sync)
{
// update your global variable
somevar = 3;
}
}
public void Return(object sender, KeyEventArgs e)
{
// lock it again if you need to deal with race conditions
// or thread safty
lock(_sync)
{
Debug.WriteLine(somevar);
}
}
Update
volatile (C# Reference)
The volatile keyword indicates that a field might be modified by
multiple threads that are executing at the same time. Fields that are
declared volatile are not subject to compiler optimizations that
assume access by a single thread. This ensures that the most
up-to-date value is present in the field at all times.

How to create thread according to integer value? [closed]

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 7 years ago.
Improve this question
I'm trying to create thread according to integer value. For example if the variable is '5', program should create 5 threads or variable is '2', program should create 2 threads, etc. But I can't understand which path I must follow.
It's just a matter of creating the Thread and start it. But I wouldn't suggest you to handle the thread explicitly, but to use Tasks or ThreadPool in order to execute multithreading work.
using System;
using System.Threading;
public class Program
{
public static void Main()
{
int numberOfRequestedThreads = 3;
for (int i = 0; i < numberOfRequestedThreads; i++)
{
var tempThread = new Thread(new ThreadStart(DoWork));
tempThread.Name = i.ToString();
tempThread.Start();
}
}
public static void DoWork()
{
Console.WriteLine("Thread#{0} is now working!", Thread.CurrentThread.Name);
}
}

How to use the thread to show something on the label on the form? [closed]

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
i have a method
public static string MyWrite2()
{
string p = "hi";
for (int i = 0; i < 20; i++)
{
p += "kk";
}
return p;
}
and i want to write a thread which when i click on btn1 it call MyWrite2 and put the result on label1, how can i do it?
You can use Invoke() method on a label1 and pass a method which does the writing as an argument to the Invoke() method.
Using anonymous method it would be sth like:
label1.Invoke(new MethodInvoker(delegate
{
label1.Text = MyWrite2();
}
));
In the other thread.

How can I convert this code from vb. net to C#? [closed]

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 6 years ago.
Improve this question
I am trying to convert vb .net code to c# but I am having problem with the following code:
Dim MI_Display_Channel As New MethodInvoker(AddressOf display_channel)
Private Sub display_channel()
TextBox1.Text = fv_channel
End Sub
How can I convert this piece of code into c#?
I see two answers machine translated where, apparently, a field initializer of an instance field, refers an instance member of the class. That is not allowed.
To be explicit:
class Xxx
{
MethodInvoker MI_Display_Channel = display_channel; // compile-time error!
void display_channel()
{
TextBox1.Text = fv_channel;
}
}
will not compile. When the field initialization is not allowed in a field initializer, use a constructor:
class Xxx
{
public Xxx() // other instance constructors may want to chain : this()
{
MI_Display_Channel = display_channel; // fine
}
MethodInvoker MI_Display_Channel; // no initializer here
void display_channel()
{
TextBox1.Text = fv_channel;
}
}
From here, you get this:
MethodInvoker MI_Display_Channel = new MethodInvoker(display_channel);
private void display_channel()
{
TextBox1.Text = fv_channel;
}
I'm not sure why it was difficult.

Need to deploy single threaded in memory store [closed]

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
Using Asp.Net 4/c#
I want to store a list of items in memory (I use the term list generically) rather than list. I need to maintain a last used date for items in the list.
Effictively I need to lock, find the earliest date, update it and unlock and return the record.
As a relative newbie, I have a couple of questions:
What is the best way to store the data;
Is there a documented locking pattern I can use to ensure thread
safety.
From your description what you want is a queue & a locking mechanism around that queue. The queue is a first in first out container, which means objects will be dequeued in the order they are enqueued, guaranteeing your update order constraint. As for the synchronization constraint, because you want to do the work inside of the lock, you'll need a lock at a higher level than your queue. Something like this should do the trick but needs to be used the correct way, as a LockingDequeu() without dispose will permanently lock the queue.
public class MyQueue<T>
{
private readonly Queue<T> internalQueue = new Queue<T>();
private readonly object queueLocker = new object();
public Enqueue(T data)
{
internalQueue(data);
}
public IDisposable LockingDequeue(out T data)
{
var queueLock = new QueueLock(queueLocker);
data = internalQueue.Dequeue();
return queueLock;
}
private class QueueLock :IDisposable
{
private readonly object lockObject;
public QueueLock(object lockObject)
{
this.lockObject = lockObject;
Monitor.Enter(lockObject);
}
public void Dispose()
{
Monitor.Exit(lockObject);
}
}
}
Understand that the LockingDequeue call needs to be used within a using block. But the calling syntaxt would look like this:
var myQueue = new MyQueue<object>();
object obj;
using(myQueue.LockingDequeue(out obj))
{
//update date
//do some work
myQueue.Enqueue(obj);
}

Categories