Say we have the following method:
private MyObject foo = new MyObject();
// and later in the class
public void PotentialMemoryLeaker(){
int firedCount = 0;
foo.AnEvent += (o,e) => { firedCount++;Console.Write(firedCount);};
foo.MethodThatFiresAnEvent();
}
If the class with this method is instantiated and the PotentialMemoryLeaker method is called multiple times, do we leak memory?
Is there any way to unhook that lambda event handler after we're done calling MethodThatFiresAnEvent?
Yes, save it to a variable and unhook it.
DelegateType evt = (o, e) => { firedCount++; Console.Write(firedCount); };
foo.AnEvent += evt;
foo.MethodThatFiresAnEvent();
foo.AnEvent -= evt;
And yes, if you don't, you'll leak memory, as you'll hook up a new delegate object each time. You'll also notice this because each time you call this method, it'll dump to the console an increasing number of lines (not just an increasing number, but for one call to MethodThatFiresAnEvent it'll dump any number of items, once for each hooked up anonymous method).
You wont just leak memory, you will also get your lambda called multiple times. Each call of 'PotentialMemoryLeaker' will add another copy of the lambda to the event list, and every copy will be called when 'AnEvent' is fired.
Well you can extend what has been done here to make delegates safer to use (no memory leaks)
Your example just compiles to a compiler-named private inner class (with field firedCount and a compiler-named method). Each call to PotentialMemoryLeaker creates a new instance of the closure class to which where foo keeps a reference by way of a delegate to the single method.
If you don't reference the whole object that owns PotentialMemoryLeaker, then that will all be garbage collected. Otherwise, you can either set foo to null or empty foo's event handler list by writing this:
foreach (var handler in AnEvent.GetInvocationList()) AnEvent -= handler;
Of course, you'd need access to the MyObject class's private members.
Yes in the same way that normal event handlers can cause leaks. Because the lambda is actually changed to:
someobject.SomeEvent += () => ...;
someobject.SomeEvent += delegate () {
...
};
// unhook
Action del = () => ...;
someobject.SomeEvent += del;
someobject.SomeEvent -= del;
So basically it is just short hand for what we have been using in 2.0 all these years.
Related
My question is from this implementation of a ThreadPool class in C++11. Following is relevant parts from the code:
whenever enqueue is called on the threadPool object, it binds the passed function with all passed arguments, to create a shared_ptr of std::packaged_task:
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
extracts the future from this std::packaged_taskto return to the caller and stores this task in a std::queue<std::function<void()>> tasks;.
In the constructor, it waits for the task in queue, and if it finds one, it executes the task:
for(size_t i = 0;i<threads;++i)
workers.emplace_back(
[this]
{
for(;;)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock,[this]{ return !this->tasks.empty(); });
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
}
);
Now, based on this, following is my questions:
If std::packaged_task was stored in a std::queue<std::function<void()>>, then it just becomes a std::function object, right? then how does it still write to the shared state of std::future extracted earlier?
If stored std::packaged_task was not just a std::function object but still a std::packaged_taskthen when a std::thread executes task() through a lambda (code inside constructor), then why doesn't it run on another thread? as std::packaged_task are supposed to run on another thread, right?
As my questions suggest, I am unable to understand the conversion of std::packaged_task into std::function and the capability of std::function to write to the shared state of std::future. Whenever I tested this code with n threads, the maximum number of thread ids I could get was n but never more than n. Here is the complete code (including that of ThreadPool and it also includes a main function which counts the number of threads created).
I have an issue with cross threading on a UI. I have read all the ways to do it and have implemented them as seen below.
public void UpdateList(object obj)
{
// do we need to switch threads?
if (listBox1.InvokeRequired)
{
MethodInvoker del = () => UpdateList(obj);
this.Invoke(del);
return;
}
// ok so now we're here, this means we're able to update the control
// so we unbox the object into a string
string text = (string)obj;
// and update
listBox1.Items.Add(text);
}
The issue comes when I try to do a
hubConnection.Start().Wait();
After that call I am trying to update my list.
Without the wait is fine. When I add the Wait it hangs on the UpdateList Invoke. There is no error...it just hangs.
I am handling this call in a button event.
Wait() is creating a deadlock on the mainthread.
Replace the hubconnection.Start.Wait() with:
await hubconnection.Start() in an async method:
public void async StartHubClickedEvent(...){
await hubconnection.Start()
}
The Microsoft Async library enables use of async/awaut on .net 4.0 and VS12.
Install-Package Microsoft.Bcl.Async
See Deadlock when thread uses dispatcher and the main thread is waiting for thread to finish
You've generated a recursive loop. Assuming an Invoke is Required, you'll call up the same method, hit if (listBox1.InvokeRequired) again (which will still pass true) and start looping as you keep calling up the same method again and again. It's better to do an If..Else pattern here where you directly invoke the change on the ListBox or simply perform the change without the invoke
An Example
if (listBox1.InvokeRequired)
{
listBox1.Invoke(()=> { listBox1.Items.Add((string)text) };
}
else
{
string text = (string)obj;
// and update
listBox1.Items.Add(text);
}
Assuming the constructor runs in the client part of the code (the one that gets translated to javascript).
The callback method onSuccess does modify the instance variables of the class.
The callback is implemented as an anonymous class so the instance of the outer class can be accessed by using OuterClass.this.
Normally in plain Java we should not do something like this because by doing so, 'this' reference can escape before the object construction is finished.
But does it also hold for the case when Java code is translated to Javascript? I assume that javascript code is executed by a single thread in a web browser so this should not be an issue (single thread => no visibility problems)?
On the one hand, you're right - the problem cannot be triggered by a separate thread, because JavaScript is single threaded.
Callback events will definitely be handled by an event handler that starts after the current event handler (the one which constructs the current object) has finished. So they will only ever see the fully constructed object.
On the other hand, you generally don't need threads to exploit the basic problem. Here's a simple example:
final A a = new A();
final B b = new B(a);
public class A {
private B b;
public void setB(final B b) {
this.b = b;
}
public void letBSaySomething() {
b.saySomething();
}
}
public class B {
private A a;
private final int some;
public B(final A a) {
this.a = a;
a.setB(this);
a.letBSaySomething();
some = 55;
a.letBSaySomething();
}
public void saySomething() {
RootPanel.get().add(new Label("Hello " + some));
}
}
This results in the output
Hello 0
Hello 55
(although 'some' is final). This happens both in GWT (compiled/uncompiled) and plain Java programs.
AsyncCallback, by itself, is just a class. When you send an RPC request in production mode, you are guaranteed that the result will come in asynchronously through XmlHttpRequest; in compiled javascript it is 100% impossible to leak the reference before construction is finished, as the callback will get called in a separate javascript execution stack.
In gwt-dev mode, however, things that should be asynchronous aren't always so. Personally, I abandoned gwt-dev over super-dev-mode, and only use gwt-dev when I really need java debugger, so I can't tell you for sure if it will be immune to construction problems or not (test it and find out!).
If you are not sending any requests in the constructor, you will be 100% safe. Just creating the async callback will only lead to problems if you are subsequently accessing OuterClass.this in unsafe ways, regardless of the classes involved.
I'm writing a program in which I need to make sure a particular function is called is not being executed in more than one thread at a time.
Here I've written some simplified pseudocode that does exactly what is done in my real program.
mutex _enqueue_mutex;
mutex _action_mutex;
queue _queue;
bool _executing_queue;
// called in multiple threads, possibly simultaneously
do_action() {
_enqueue_mutex.lock()
object o;
_queue.enqueue(o);
_enqueue_mutex.unlock();
execute_queue();
}
execute_queue() {
if (!executing_queue) {
_executing_queue = true;
enqueue_mutex.lock();
bool is_empty = _queue.isEmpty();
_enqueue_mutex.lock();
while (!is_empty) {
_action_mutex.lock();
_enqueue_mutex.lock();
object o = _queue.dequeue();
is_empty = _queue.isEmpty();
_enqueue_mutex.unlock();
// callback is called when "o" is done being used by "do_stuff_to_object_with_callback" also, this function doesn't block, it is executed on its own thread (hence the need for the callback to know when it's done)
do_stuff_to_object_with_callback(o, &some_callback);
}
_executing_queue = false;
}
}
some_callback() {
_action_mutex.unlock();
}
Essentially, the idea is that _action_mutex is locked in the while loop (I should say that lock is assumed to be blocking until it can be locked again), and expected to be unlocked when the completion callback is called (some_callback in the above code).
This, does not seem to be working though. What happens is if the do_action is called more than once at the same time, the program locks up. I think it might be related to the while loop executing more than once simultaneously, but I just cant see how that could be the case. Is there something wrong with my approach? Is there a better approach?
Thanks
A queue that is not specifically designed to be multithreaded (multi-producer multi-consumer) will need to serialize both eneueue and dequeue operations using the same mutex.
(If your queue implementation has a different assumption, please state it in your question.)
The check for _queue.isEmpty() will also need to be protected, if the dequeue operation is prone to the Time of check to time of use problem.
That is, the line
object o = _queue.dequeue();
needs to be surrounded by _enqueue_mutex.lock(); and _enqueue_mutex.unlock(); as well.
You probably only need a single mutex for the queue. Also once you've dequeued the object, you can probably process it outside of the lock. This will prevent calls to do_action() from hanging too long.
mutex moo;
queue qoo;
bool keepRunning = true;
do_action():
{
moo.lock();
qoo.enqueue(something);
moo.unlock(); // really need try-finally to make sure,
// but don't know which language we are using
}
process_queue():
{
while(keepRunning)
{
moo.lock()
if(!qoo.isEmpty)
object o = qoo.dequeue();
moo.unlock(); // again, try finally needed
haveFunWith(o);
sleep(50);
}
}
Then Call process_queue() on it's own thread.
I have a backgroundworker_dowork() event in C# .Net 4, that calls three methods, and I want them to execute synchronously.
Given my constraints, method 3 must execute after method 2, and method 2 must execute after method 1.
However, in the BackgroundWorker all three methods are executed asynchronously.
How can I change this?
private void bgwLoading_DoWork(object sender, DoWorkEventArgs e)
{
ArrayList a = (ArrayList)e.Argument;
string[] fileNames = (string[])a[0];
bool isLoad = (bool)a[1];
this.loadMultiImages(fileNames, isLoad);
}
private void loadMultiImages(string[] fileNames, bool isLoad)
{
// I want to execute the following codes sequentially.
Bitmap newBtmap = saveJpeg();
this.SafeInvoke(d => d.imageList.Images.Add(newBtmap));
}
Since SafeInvoke() takes less time than saveJpeg(), it starts executing before the saveJpeg() is done, changing the flow of the execution I want.
If method 3 depends on method 2 and method 2 depends on method 1, then there is only one way to execute them: sequentially. Even if you task multiple threads with executing them, you'll still have to execute the methods in order 1->2->3.
You can use various constructs to force method 2 to wait for method 1 and method 3 to wait for method 2, but you're still fundamentally executing the methods synchronously so you might as well just use 1 thread to execute all 3 methods.
You may want something like this. Use the RunWorkerCompleted event to call a method after the background operation completes:
var bg1 = new System.ComponentModel.BackgroundWorker();
var bg2 = new System.ComponentModel.BackgroundWorker();
var bg3 = new System.ComponentModel.BackgroundWorker();
bg1.RunWorkerCompleted += (s, e) =>
{
bg2.RunWorkerAsync();
};
bg2.RunWorkerCompleted += (s, e) =>
{
bg3.RunWorkerAsync();
};
bg1.RunWorkerAsync();
But, I'm not sure on the effectiveness of this pattern. If you want functions called synchronously, then call them synchronously. There's probably a better way to do that than using background workers.
If you want to run 3 procedures synchronously in the background, just call them synchronously in the background thread:
var bg1 = new System.ComponentModel.BackgroundWorker();
bg1.DoWork += (s, e) =>
{
Process1();
Process2();
Process3();
};
bg1.RunWorkerAsync();