UPDATE: turns out that this is a problem with the Mono compiler used by Unity3D. I'm not sure if the current version of Mono (3.10.0) fixes it, but the old version used in the engine (2.0.5) seems to not implement this feature for delegates, or simply work as it should.
At some point in a game I'm developing (in the Unity3D engine), the player unlocks several items at once. For each of them I must present a simple information dialog that the user must click to advance to the next, until all have been read.
I have a simple C# static method to show a dialog (just a colored overlay with some text in Unity, and NOT in any way related to C# UI frameworks):
ConfirmationDialog.Create("Item X Unlocked!", callback);
When the user finally presses the dialog, callback is called.
I wanted to chain all dialogs so that each one is only created when the previous is clicked on, so I tried this:
Action callback = delegate {};
foreach (string item in unlockedItems) {
var cb = callback; // I though this would create a closure for delegates too
callback = (() => ConfirmationDialog.Create(item + " Unlocked!", cb));
}
callback();
This made sense in my head, as the anonymous function would use a different "cb" delegate in each iteration of the cycle. It seems I'm mistaken, though, as this code seems to result in the same dialog being repeatedly called when clicked, as would happen in a recursive function (which I guess is what it became).
I know I can, for example, do int value = i; inside a for loop (where i is the loop iterator) to use the correct value of i inside the anonymous function (I found a lot of material on this). Delegates seem different, but what in particular makes them not work in the same way? Or am I doing something terribly wrong? Could I do this chaining in some similar way? I say "similar" because I can certainly think of doing this in other - more complicated - ways...
Note: please DO correct me if my use of the words "closure", "delegate", etc, is not right :)
Do you have control over the ConfirmationDialog.Create("Item X Unlocked!", callback); API? If so, instead of taking a callback, you should look at refactoring that to use Task. If you had that, you could simply chain a bunch of tasks as continuations and have them execute one after the other.
I know with game development, these things are often quite asynchronous in nature, the way UI gets shown and subsequently reacted to ... so you could use TaskCompletionSource so you have a handle to something that you can signal that your task is done.
Related
So, I as trying to create an "Open world exploration" game in C# WinForms, And while coding the mining, (which works just fine), I encountered a problem with saving the number of broken blocks to the inventory (a label). Basically, for every block player breaks, it gets added to the inventory as inventoryWrite.Text = $"Grass: {grassHolder}, Rock: {rockHolder}";.
Now, the thing is, sometimes, even though I use the ++ operator, it adds up to 4 to the inventory. I'm citing the code below.
private void Remove(object sender, EventArgs e, PictureBox itm)
{
if (itm.BorderStyle == BorderStyle.FixedSingle)
{
if (itm.Tag.Equals("grass") && items.Contains(itm))
{
grassHolder++;
itm.Tag = "";
}
if (itm.Tag.Equals("rock") && items.Contains(itm))
{
rockHolder++;
itm.Tag = "";
}
if (itm.Tag.Equals("dio") && items.Contains(itm))
{
dioHolder++;
itm.Tag = "";
}
this.Controls.Remove(itm);
items.Remove(itm);
}
}
I update the inventory in a public loop, don't worry about that (interval is 1ms). But I don't think that's the problem, since I tried putting it in the Remove() function, and nothing seemed to change.
I've even double locked the if statement, but nothing! It still adds more than 1. Can anybody tell me how to solve this? Thank you a lot.
EDIT:
As a reply to Ronald's comment, the if statement is called ONLY when the block is selected. ONLY once when the method is called.
There are too many points to cover in a comment and so I've had to enter an answer.
In itself the ++ operator is not the issue and will always behave as it should, but as someone reviewing a small piece of code the following points crop up.
grassHolder, rockHolder, dioHolder appear to have
accessibility beyond this function and so could be altered
elsewhere.
Function void Remove(object sender, EventArgs e, PictureBox itm) appears to be an event handler and yet there is no locking mechanism to ensure that the externally accessible parameters are not changed or used elsewhere whilst the function code is executed. Specifically items which is appears to be a collection of sorts and is used both in logic to determine whether parameters in (1) are incremented, but also has its contents changed within the function.
From comments made it would appear that this logic is run in
response to user interaction, maybe by use of a mouse button or key
event. Is this base event de-bounced to ensure that multiple
triggers aren't handled?
Your statement "saving the number of broken blocks to the inventory (a label)." Implies that you are storing game data within the UI. This should be avoided as it ties game data directly to the UI implementation and therefore makes it difficult to alter the game, but also ties any handling of game data directly to the UI thread.
Recommended actions:
Ensure that the parameters in question are not accessed and altered
elsewhere causing the issue seen.
Utilize a lock(x) statement to ensure that items is not changed
whilst this function is being executed. More information here
De-bounce the mouse button or key click that triggers this function
to ensure that multiple events aren't triggered. This is performed
by placing a minimum time between event triggers. A minimum time
period of say 150ms would be a good starting point. This would equate to a reasonably quick, conscious user action, but be slower than multiple events triggered by partial/poor switch contact. Incidentally this is especially true on touch screen interfaces.
Consider controlling access to global parameters through use of
access functions. For example
int IncrementRockHolder(){ rockHolder++;} Although implementation may appear onerous, they can greatly help with debugging as call stack information is then available showing what code is calling the function and thus making the change.
Implement a game engine class to control access to game data and implement game logic. This
would allow you to unit test game functionality whilst also freeing
it from UI implementation and restrictions.
I received a win-form application with following pseudo-code. Most of the current function codes are written in the code behind the forms as those functions interact with form controls.
loop through device connections
connect to a device
call a specific function, do some specific work
close the device connection
There are 10 different functions (entirely varied signatures from one another). First version of the application repeated step 1, 2, 4 for all the 10 functions. The second version optimized it by adding select case statement with numeric values to call the functions within device connection-loop.
However I feel that function delegates could improve this code.
But I am quite lost in making an analogue to the delegate concept with what I have in hand. Can I use delegates in this situation and how should I approach it in terms of the application execution/code design?
it's hard to tell having only the pseudo-code but IMO you don't need a delegate - either use Action<...> or Func<...> depending on if you need a result or not.
For example it could look something like this:
static void DoForAllDevices(Action<Connection> action)
{
foreach(var device in myDevices)
{
using (var connection = ConnectTo(device))
{
action(connection);
} // typically Dispose will handle the closing
}
}
then you just have to call it like this
DoForAllDevices(connection => myFirstFun(connection, additionalParameter);
now of course you can add all kind of exception-Handling, etc. inside DoForAllDevices - should be easy to do
I'm having a little trouble concisely describing what it is that I'm trying to do, which is hurting my ability to search for an answer. I'll try to be specific with my problem, if anyone could give a suggestion or point me in the direction of what to study, I'd greatly appreciate it.Tr
I'm trying to program a GUI version of the cardgame Dominion, where playing different cards will yield different results and choices. Many of these cards have similar starting choices (e.g. select a card from your hand and trash it/look at enemy hand), but different ending choices (e.g. upgrade that trashed card/give trashed card to another player). upon playing a card, the program looks for the unique numeric card code and begins executing code specific to that card.
Here's where I'm hung up:
I'd like to have more general methods that listen for user input INSIDE the unique card-code, but I keep getting errors. Ideally, I'd be able to do something like
for(int i = 0; i < totalPlayers; i++)
{
showEnemyHand(i);
}
or
for(int i = 0; i < totalPlayers; i++)
{
thiefEffect(i);
}
within a 'buttonclicked' event (the "play card" button, specifically.) The showEnemyHand(int) and thiefEffect(int) method would wait for user input, store responses, and then return right back to the for loop that it was called from, but its not as easy as I'd originally hoped.
I'm suffering most from not even knowing what it is that I should be searching for. I've been reading up on event handling and delegates, and I'm not sure that's what I need. Can anyone point me in the direction of what I need to learn, or maybe give me the topic of what I'm trying to solve so I can search for it a little easier? (of course, helping me solve it would be appreciated too =D)
Thanks a bunch!
Jake
Your solution would be fine for a command line based game, in a language with continuations/coroutines, or maybe in a multi-threaded application where showEnemyHand etc would block on user input. For a GUI-based game, an event driven architecture is really what would work best for you, so in principle I'd suggest learning more about it.
But if you really want to do that using a loop, I'd suggest then reading about threading and blocking calls. Once you understand the concepts, you should be able to:
Create a separate thread to host your loop;
Create a lock that will block execution until the user inputs something (see the example in the linked question);
Use that lock in your loop and on the callback for user input:
In the beginning of your loop, you wait on your lock;
When the user inputs something (which you'll detect using an event handler - see the docs for the particular GUI framework you're using) you save which action was chosen and frees the lock;
Your loop will automatically continue, reading the saved action and performing an iteration, until it reachs the same point again and waits for another user input.
Whether this method is easier or harder than coding your rules using the event driven logic, it's debatable. The same can be said about coroutines (though being less experienced with that, I can not opinate). The pointers I gave should help you get started though.
I recently asked about functional programs having no side effects, and learned what this means for making parallelized tasks trivial. Specifically, that "pure" functions make this trivial as they have no side effects.
I've also recently been looking into LINQ and lambda expressions as I've run across examples many times here on StackOverflow involving enumeration. That got me to wondering if parallelizing an enumeration or loop can be "easier" in C# now.
Are lambda expressions "pure" enough to pull off trivial parallelizing? Maybe it depends on what you're doing with the expression, but can they be pure enough? Would something like this be theoretically possible/trivial in C#?:
Break the loop into chunks
Run a thread to loop through each chunk
Run a function that does something with the value from the
current loop position of each thread
For instance, say I had a bunch of objects in a game loop (as I am developing a game and was thinking about the possibility of multiple threads) and had to do something with each of them every frame, would the above be trivial to pull off? Looking at IEnumerable it seems it only keeps track of the current position, so I'm not sure I could use the normal generic collections to break the enumeration into "chunks".
Sorry about this question. I used bullets above instead of pseudo-code because I don't even know enough to write pseudo-code off the top of my head. My .NET knowledge has been purely simple business stuff and I'm new to delegates and threads, etc. I mainly want to know if the above approach is good for pursuing, and if delegates/lambdas don't have to be worried about when it comes to their parallelization.
First off, note that in order to be "pure" a method must not only have no side effects. It must also always return the same result when given the same arguments. So, for example, the "Math.Sin" method is pure. You feed in 12, it gives you back sin(12) and it is the same every time. A method GetCurrentTime() is not pure even if it has no side effects; it returns a different value every time you call it, no matter what arguments you pass in.
Also note that a pure method really ought not to ever throw an exception; exceptions count as observable side effects for our purposes.
Second, yes, if you can reason about the purity of a method then you can do interesting things to automatically parallelize it. The trouble is, almost no methods are actually pure. Furthermore, suppose you do have a pure method; since a pure method is a perfect candidate for memoization, and since memoization introduces a side effect (it mutates a cache!) it is very attractive to take what ought to be pure methods and then make them impure.
What we really need is some way to "tame side effects" as Joe Duffy says. Some way to draw a box around a method and say "this method isn't side-effect-free, but its side effects are not visible outside of this box", and then use that fact to drive safe automatic parallelization.
I'd love to figure out some way to add these concepts to languages like C#, but this is all totally blue-sky open-research-problem stuff here; no promises intended or implied.
Lambda's should be pure. And then the FrameWork offers automatic paralellization with a simple .AsParallel addition to a LINQ query (PLINQ).
But it is not automatic or guaranteed, the programmer is responsible to make/keep them pure.
Whether or not a lambda is pure is tied to what it is doing. As a concept it is neither pure or impure.
For example: The following lambda expression is impure as it is reading and writing a single variable in the body. Running it in parallel creates a race condition.
var i = 0;
Func<bool> del = () => {
if ( i == 42 ) { return true; }
else ( i++ ) { return false; }
};
Contrarily the following delegate is pure and has no race conditions.
Func<bool> del = () => true;
As for the loop part, you could also use the Parallel.For and Parallel.ForEach for the example about the objects in a game. This is also part of .net 4 , but you can get it as a download.
There is a 13 parts reading that discuss about the new Parallelism support in .NET 4.0 here. It includes discussion on LINQ and PLINQ as well in Part 7. It is a great read, so check it out
This question already has answers here:
Where do I use delegates? [closed]
(8 answers)
Closed 9 years ago.
Duplicate:
Difference between events and delegates and its respective applications
What are the advantages of delegates?
Where do I use delegates?
I wonder what the purpose of delegates is. I haven't used them that much and can't really think of something.
In my courses, it's written that a delegate is a blue-print for all methods that comply with its signature.
Also, you can add multiple methods to one delegate, and then they'll be executed after eachother in the order they were added. Which is probably only usefull for methods that affect local variables or methodes that don't return any values.
I've read that C# implements Events as delegates, which is documented as being:
//Summary: Represents the method that
will handle an event that has no event
data.
//Parameters:
//sender: The source of the event.
//e: An System.EventArgs that contains no event data.
[Serializable]
[ComVisible(true)]
public delegate void EventHandler(object sender, EventArgs e);
Still, it's kinda confusing. Can someone give a good, usefull example of this concept?
Yeah,
You're almost there. A delegate refers to a method or function to be called. .NET uses the Events to say.. when someones presses this button, I want you to execute this piece of code.
For example, in the use of a GPS application:
public delegate void PositionReceivedEventHandler(double latitude, double longitude);
This says that the method must take two doubles as the inputs, and return void. When we come to defining an event:
public event PositionReceivedEventHandler PositionReceived;
This means that the PositionRecieved event, calls a method with the same definition as the
PositionReceivedEventHandler delegate we defined. So when you do
PositionRecieved += new PositionReceivedEventHandler(method_Name);
The method_Name must match the delegate, so that we know how to execute the method, what parameters it's expecting. If you use a Visual Studio designer to add some events to a button for example, it will all work on a delegate expecting an object and an EventArgs parameter.
Hope that helps some...
As you noted a delegate is a way to create a signature for an method call. There are many great examples of using delegates, but the one that really opened my mind is this example.
public delegate Duck GetDuckDelegate();
public GetDuckDelegate GiveMeTheDuckFactoryMethod(string type)
{
switch(type)
{
case "Rubber":
return new GetDuckDelegate(CreateRubberDuck);
case "Mallard":
return new GetDuckDelegate(CreateMallardDuck);
default:
return new GetDuckDelegate(CreateDefaultDuck);
}
}
public Duck CreateRubberDuck()
{
return new RubberDuck();
}
public Duck CreateMallardDuck()
{
return new MallardDuck();
}
public Duck CreateDefaultDuck()
{
return new Duck();
}
Then to use it
public static void Main() {
var getDuck = GiveMeTheDuckFactoryMethod("Rubber");
var duck = getDuck();
}
Arguably, the Factory pattern would be a better method for this, but I just thought up this example on the fly and thought it proved the point of how delegates can be treated as objects
Delegates allow you to pass methods around like values.
For example, .Net has a method called Array.ForEach that takes a delegate and an array, and calls the delegate on each element of the array.
Therefore, you could write,
int[] arr = new int[] { 1, 2, 4, 8, 16, 32, 64 };
Array.ForEach(arr, new Action<int>(Console.WriteLine));
This code will call Console.WriteLine for each number in the array.
There are many things you can do by making functions that take delegates, especially when combined with anonymous methods. For examples, look at LINQ.
Many people initially get confused with the real need for delegates and events. I was one of them and it took me some time to figure it out :-). Recently answered a similar query in ASP.NET forums and thought it would be good if I create a blog post on this topic! Here was the query:
"I was reading an example somewhere of a Bank Class that if the minimum balance is reached you need to inform the rest of the app that the min has reached, but can't we do that by just calling a normal method.
for example: lets say when we deduct some amount from the balance and if minimum reached then call some method to take some action, I am totally missing why do we need delegates and custom events here?"
Thing is in the Bank case, you can definitely call a method, but then it would be simple procedural programming, we need event based programming when we want our code to respond to some events generated by a system.
For eg.: think that windows OS is a system, and we are writing a code (in any language) where we want to capture an event like mouse_click(). Now how would our program know that a mouse click has occured? We can use low level code for it, but since OS is already handling low level code, its best to capture an event raised by the OS.
In other terms, the moment a mouse_click() happens the OS fires an event. The OS doesnt care who captures this event and uses it, it just sends out a notification. Then any code (like ours) can capture that event and use it accordingly. This saves us a lot of time to write code for the same ourselves. And other programs too can use the same event and handle it accordingly.
Similarly, the banking system can be huge, and many other outside applications might be accessing it. The banking system does not know how many such applications there are which need it, or are dependent on it, and how would they handle certain situations like when balance is low, so it simply fires an event whenever low balance occurs, and this event can be used by any other code, besides banking code itself.
Note that each susbcriber to that event can handle that event independently, for eg. the banking code might stop something from executing if balance is low, some other reporting app might send an email in such a case, or some ATM code can stop a particualr transaction and notify the user that balance is low.
Hope this clears things a bit!
I can provide you with an example using a web application architecture:
Generally, with a web application you can provide a front controller that receives requests from many clients. We could put all our methods within the front controller for dealing with the many different types of requests from the clients. However, this get a little cumbersome. Instead we can use delegates to encapsulate functionality for different requests. We could have:
Authentication Delegate
User Management Delegate
and so on. So it's a neat way to split up functionality into logical chunks - delegates. The Struts framework is based on this way of working (the ActionServlet and Action classes).
There are lots of excellent articles explaining delegates - here are some good ones:
Delegates and events
C# Delegates Explained
Delegates in C#
Delegates, to my understanding, provides a way of specializing the behavior of a class without subclassing it.
Some classes have complex generic behavior, but are still meant to be specialized. Think of a Window class in a GUI framework: A Window can propably do a lot on it's own, but you would most likely still want to specialize it in some way. In some frameworks, this is done via inheritance. A different way of doing it is with delegates. Say you want something to happen when the Window resizes: Your delegate class can then implement a method called onWindowResize (provided of course that the Window class supports this), which gets called whenever the Window resizes and is responsible for any specialized behavior when the Window resizes.
I'm not going to argue the merits of delegation over inheritance, but suffice it to say that there are many who feel that delegation is "cleaner" than inheritance.