How to get an unique identifier of a function - c#

I have a function which takes an object of a custom class. A member of this object should store an identifier of that function (or a 'reference' to that function) so that the function can determine whether it was called before with this object.
What is a suitable identfier for this purpose?
I am not necessarily talking about the function name, because overloaded functions share the same name, so this doesn't work.
Is the function address (as used für delegates) a proper way? I am pretty sure that this will work, but not 100% sure. Or may the function be moved around by the garbage collector like regular objects?
Is there maybe another, better way to get a 'function ID'?
Edit
Here's an example to demonstrate my requirement (pseudo-code used):
void WorkerFunction (CFuncStep i_oFS)
{
if (i_oFS.FunctionID == WorkerFunction.FunctionID)
{
// continue work
}
else
{
// start work
i_oFS.FunctionID = WorkerFunction.FunctionID;
}
if (finished_work)
i_oFS.FunctionID = null;
}
The purpose is saving the operation state and later continuing an operation in a called function. This makes sense in cases e.g. where the function does network communication and has to wait for the reply. The func returns immediately so that the thread can do other work. Later it comes back to fetch the reply.
I could use a separate thread, but I want to avoid the overhead of thread sync here, because it would not just be 1 add. thread, but quite some.

#BenVoigt: Thanks for the hint at MethodHandle!
This is absolutely what I needed. I found a usage example at the SO post 'Can you use reflection to find the name of the currently executing method?'
Here's my solution:
using namespace System::Reflection;
ref class CFuncStep
{
public:
int m_iStep;
MethodBase^ m_oMethod;
String^ m_sName;
};
void workerfunction (CFuncStep^ i_oFS)
{
MethodBase^ oMethod = MethodBase::GetCurrentMethod ();
if (oMethod != i_oFS->m_oMethod)
{
i_oFS->m_iStep = 1;
i_oFS->m_oMethod = MethodBase::GetCurrentMethod ();
i_oFS->m_sName = i_oFS->m_oMethod->Name;
}
switch (i_oFS->m_iStep)
{
case 1:
case 2:
case 3:
i_oFS->m_iStep++;
break;
case 4:
i_oFS->m_iStep = 0;
i_oFS->m_oMethod = nullptr;
i_oFS->m_sName = nullptr;
}
};
int main()
{
CFuncStep^ oFS = gcnew CFuncStep;
do
{
workerfunction (oFS);
}
while (oFS->m_iStep > 0);
return 0;
}

Related

Determine execution flow with nullchecks to operate components as best as possible

Many times I find myself in the need of checking which type of componenent am I handling to make the corresponding operations.
For example:
bool isFooAType = someGameObject.GetComponent<FooA>() != null;
bool isFooBType = someGameObject.GetComponent<FooB>() != null;
if (isFooAType) {
FooA myFooA = someGameObject.GetComponent<FooA>();
//FooA Operations....
}
if (isFooBType) {
FooA myFooB = someGameObject.GetComponent<FooB>();
//FooB Operations....
}
Is there a more condensed or more elegant way to determine the flow of execution depending on the component type to handle the corresponding operations and even maybe avoid doing GetComponent twice (one to check if its null + get again to operate the component in the code successively)?
As mentioned there is TryGetComponent so you do simply
if (someGameObject.TryGetComponent<FooA>(out var fooA))
{
fooA.DoSomething();
}
if (someGameObject.TryGetComponent<FooB>(out var fooB))
{
fooB.DoSomehtingElse();
}
If this is not available (and only then) e.g. due to older Unity versions rather still make the call ONCE and do
var fooA = someGameObject.GetComponent<FooA>();
var fooB = someGameObject.GetComponent<FooB>();
if (fooA)
{
fooA.DoSomething();
}
if (fooB)
{
fooB.DoSomehtingElse();
}
In general you might want both to be exclusive by using else if.
And in particular if both are basically implementing the same method you would rather use a common base class or interface and have only one single TryGetComponent or GetComponent call.

Break out of parent function?

public static void CacheUncachedMessageIDs(List<int> messageIDs)
{
var uncachedRecordIDs = LocalCacheController.GetUncachedRecordIDs<PrivateMessage>(messageIDs);
if (!uncachedRecordIDs.Any()) return;
using (var db = new DBContext())
{
.....
}
}
The above method is repeated regularly throughout the project (except with different generics passed in). I'm looking to avoid repeated usages of the if (!uncachedRecordIDs.Any()) return; lines.
In short, is it possible to make the LocalCacheController.GetUncachedRecordIDs return the CacheUncachedMessageIDs method?
This will guarantee a new data context is not created unless it needs to be (stops accidentally forgetting to add the return line in the parent method).
It is not possible for a nested method to return from parent method.
You can do some unhandled Exception inside GetUncachedRecordIDs, that will do the trick, but it is not supposed to do this, so it creates confusion. Moreover, it is very slow.
Another not suggested mechanic is to use some goto magic. This also generates confusion because goto allows unexpected behaviour in program execution flow.
Your best bet would be to return a Result object with simple bool HasUncachedRecordIDs field and then check it. If it passes, then return. This solution solves the problem of calling a method, which is Any() in this case.
var uncachedRecordIDsResult = LocalCacheController.GetUncachedRecordIDs<PrivateMessage>(messageIDs);
if(uncachedRecordIDsResult.HasUncachedRecordIDs) return;
My reasoning for lack of this feature in the language is that calling GetUncachedRecordIDs in basically any function would unexpectedly end that parent function, without warning. Also, it would intertwine closely both functions, and best programming practices involve loose coupling of classes and methods.
You could pass an Action to your GetUncachedRecordIDs method which you only invoke if you need to. Rough sketch of the idea:
// LocalCacheController
void GetUncachedRecordIDs<T>(List<int> messageIDs, Action<List<int>> action)
{
// ...
if (!cached) {
action(recordIds);
}
}
// ...
public static void CacheUncachedMessageIDs(List<int> messageIDs)
{
LocalCacheController.GetUncachedRecordIDs<PrivateMessage>(messageIDs, uncachedRecordIDs => {
using (var db = new DBContext())
{
// ...
}
});
}

what does callback mean? [duplicate]

What's a callback and how is it implemented in C#?
I just met you,
And this is crazy,
But here's my number (delegate),
So if something happens (event),
Call me, maybe (callback)?
In computer programming, a callback is executable code that is passed as an argument to other code.
—Wikipedia: Callback (computer science)
C# has delegates for that purpose. They are heavily used with events, as an event can automatically invoke a number of attached delegates (event handlers).
A callback is a function that will be called when a process is done executing a specific task.
The usage of a callback is usually in asynchronous logic.
To create a callback in C#, you need to store a function address inside a variable. This is achieved using a delegate or the new lambda semantic Func or Action.
public delegate void WorkCompletedCallBack(string result);
public void DoWork(WorkCompletedCallBack callback)
{
callback("Hello world");
}
public void Test()
{
WorkCompletedCallBack callback = TestCallBack; // Notice that I am referencing a method without its parameter
DoWork(callback);
}
public void TestCallBack(string result)
{
Console.WriteLine(result);
}
In today C#, this could be done using lambda like:
public void DoWork(Action<string> callback)
{
callback("Hello world");
}
public void Test()
{
DoWork((result) => Console.WriteLine(result));
DoWork(Console.WriteLine); // This also works
}
Definition
A callback is executable code that
is passed as an argument to other code.
Implementation
// Parent can Read
public class Parent
{
public string Read(){ /*reads here*/ };
}
// Child need Info
public class Child
{
private string information;
// declare a Delegate
delegate string GetInfo();
// use an instance of the declared Delegate
public GetInfo GetMeInformation;
public void ObtainInfo()
{
// Child will use the Parent capabilities via the Delegate
information = GetMeInformation();
}
}
Usage
Parent Peter = new Parent();
Child Johny = new Child();
// Tell Johny from where to obtain info
Johny.GetMeInformation = Peter.Read;
Johny.ObtainInfo(); // here Johny 'asks' Peter to read
Links
more details for C#.
A callback is a function pointer that you pass in to another function. The function you are calling will 'callback' (execute) the other function when it has completed.
Check out this link.
If you referring to ASP.Net callbacks:
In the default model for ASP.NET Web
pages, the user interacts with a page
and clicks a button or performs some
other action that results in a
postback. The page and its controls
are re-created, the page code runs on
the server, and a new version of the
page is rendered to the browser.
However, in some situations, it is
useful to run server code from the
client without performing a postback.
If the client script in the page is
maintaining some state information
(for example, local variable values),
posting the page and getting a new
copy of it destroys that state.
Additionally, page postbacks introduce
processing overhead that can decrease
performance and force the user to wait
for the page to be processed and
re-created.
To avoid losing client state and not
incur the processing overhead of a
server roundtrip, you can code an
ASP.NET Web page so that it can
perform client callbacks. In a client
callback, a client-script function
sends a request to an ASP.NET Web
page. The Web page runs a modified
version of its normal life cycle. The
page is initiated and its controls and
other members are created, and then a
specially marked method is invoked.
The method performs the processing
that you have coded and then returns a
value to the browser that can be read
by another client script function.
Throughout this process, the page is
live in the browser.
Source: http://msdn.microsoft.com/en-us/library/ms178208.aspx
If you are referring to callbacks in code:
Callbacks are often delegates to methods that are called when the specific operation has completed or performs a sub-action. You'll often find them in asynchronous operations. It is a programming principle that you can find in almost every coding language.
More info here: http://msdn.microsoft.com/en-us/library/ms173172.aspx
Dedication to LightStriker:
Sample Code:
class CallBackExample
{
public delegate void MyNumber();
public static void CallMeBack()
{
Console.WriteLine("He/She is calling you. Pick your phone!:)");
Console.Read();
}
public static void MetYourCrush(MyNumber number)
{
int j;
Console.WriteLine("is she/he interested 0/1?:");
var i = Console.ReadLine();
if (int.TryParse(i, out j))
{
var interested = (j == 0) ? false : true;
if (interested)//event
{
//call his/her number
number();
}
else
{
Console.WriteLine("Nothing happened! :(");
Console.Read();
}
}
}
static void Main(string[] args)
{
MyNumber number = Program.CallMeBack;
Console.WriteLine("You have just met your crush and given your number");
MetYourCrush(number);
Console.Read();
Console.Read();
}
}
Code Explanation:
I created the code to implement the funny explanation provided by LightStriker in the above one of the replies. We are passing delegate (number) to a method (MetYourCrush). If the Interested (event) occurs in the method (MetYourCrush) then it will call the delegate (number) which was holding the reference of CallMeBack method. So, the CallMeBack method will be called. Basically, we are passing delegate to call the callback method.
Please let me know if you have any questions.
Probably not the dictionary definition, but a callback usually refers to a function, which is external to a particular object, being stored and then called upon a specific event.
An example might be when a UI button is created, it stores a reference to a function which performs an action. The action is handled by a different part of the code but when the button is pressed, the callback is called and this invokes the action to perform.
C#, rather than use the term 'callback' uses 'events' and 'delegates' and you can find out more about delegates here.
callback work steps:
1) we have to implement ICallbackEventHandler Interface
2) Register the client script :
String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
String callbackScript = "function UseCallBack(arg, context)" + "{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallBack", callbackScript, true);
1) from UI call Onclient click call javascript function for EX:- builpopup(p1,p2,p3...)
var finalfield= p1,p2,p3;
UseCallBack(finalfield, ""); data from the client passed to server side by using UseCallBack
2) public void RaiseCallbackEvent(string eventArgument) In eventArgument we get the passed data
//do some server side operation and passed to "callbackResult"
3) GetCallbackResult() // using this method data will be passed to client(ReceiveServerData() function) side
callbackResult
4) Get the data at client side:
ReceiveServerData(text) , in text server response , we wil get.
A callback is a function passed as an argument to another function. This technique allows a function to invoke the parameter function argument and even to pass a value back to the caller. A callback function can be designed to run before/after the function has finished and can pass a value.
It is a kind of construct where you call a long running function and ask him to call you back once it has finished with can return a parameter result to the caller.
It's like someone calls you in the middle of your work asking for status and you say "you know what give me 5 min and i will call you back" and at the end you call him to update. If you are a function the caller just added and passed another function that you invoked at the end. This can simpley be written in C# as:
public void VinodSrivastav(Action statusUpdate){
//i am still here working..working
//i have finished, calling you
statusUpdate();
}
//invokes
stackoverflow.VinodSrivastav((cam) => {
Console.Write("Is it finished");
});
The one simple example is the iterator function where the return will be multiple times, one can argue that we have yield for it:
public void IntreationLoop(int min, int max,Action<int> Callback)
{
for(int i = min;i<= max;i++)
Callback(i);
}
//call
IntreationLoop(5,50,(x) => { Console.Write(x); }); //will print 5-50 numbers
In the code above the function return type is void but it has an Action<int> callback which is called and sends each item from the loop to the caller.
The same thing can be done with if..else or try..catch block as:
public void TryCatch(Action tryFor,Action catchIt)
{
try{
tryFor();
}
catch(Exception ex)
{
Console.WriteLine($"[{ex.HResult}] {ex.Message}");
catchIt();
}
}
And call it as:
TryCatch(()=>{
int r = 44;
Console.WriteLine("Throwing Exception");
throw new Exception("something is wrong here");
}, ()=>{
Console.WriteLine("It was a mistake, will not try again");
});
In 2022 we have Func & Action doing the same, please see the demo code below which shows how this can be be used:
void Main()
{
var demo = new CallbackDemo();
demo.DoWork(()=> { Console.WriteLine("I have finished the work"); });
demo.DoWork((r)=> { Console.WriteLine($"I have finished the work here is the result {r}"); });
demo.DoWork(()=> { Console.WriteLine($"This is passed with func"); return 5;});
demo.DoWork((f)=> { Console.WriteLine($"This is passed with func and result is {f}"); return 10;});
}
// Define other methods and classes here
public class CallbackDemo
{
public void DoWork(Action actionNoParameter)
{
int a = 5;
int b = 10;
//i will do th maths and call you back
int result = a + b;
//callback
actionNoParameter(); //execute
Console.WriteLine($"[The Actual Result is {result}]");
}
public void DoWork(Action<int> actionWithParameter)
{
int a = 5;
int b = 10;
//i will do th maths and call you back
int result = a + b;
//callback
actionWithParameter(result); //execute
Console.WriteLine($"[The Actual Result is {result}]");
}
public void DoWork(Func<int> funcWithReturn)
{
int a = 5;
int b = 10;
//i will do th maths and call you back
int result = a + b;
//callback
int c = funcWithReturn(); //execute
result += c;
Console.WriteLine($"[The Actual Result is {result}]");
}
public void DoWork(Func<int,int> funcWithParameter)
{
int a = 5;
int b = 10;
//i will do th maths and call you back
int result = a + b;
//callback
result += funcWithParameter(result); //execute
Console.WriteLine($"[The Actual Result is {result}]");
}
}

Is this design for data validation on a class a good idea?

I've got this class, let's call it Refund (because that's what it's called). I want to validate some things about this Refund and the Customer it's attached to, and I want to make these validations re-orderable, because the first one that trips will be stored as the reject reason on the Refund, and also some of them are likely to be more resource-intensive than others and more likely to be tripped, so I'd like to be able to easily reorder their execution so that I could squeeze some performance out if I need to.
All of the validation methods will take a Refund object and return a boolean denoting whether the validation has passed or failed. So, I was thinking, why not make a queue (or other data structure) to hold delegates/lambdas/anonymous functions, each representing a validation method? Then, just passing the Refund into some kind of static Validate(Refund refundToValidate) method on some Validator class. This method would walk through the array of delegates, calling each in sequence, and returning false if one of them produced false.
Is this a good idea or a stupid idea? If it's a good idea, can you point me to a resource somewhere or name a pattern that I am inadvertantly implementing, so that I know I'm doing it right? If it's a stupid idea, why and what should I be doing differently?
EDIT: here's what I've got so far-
public static class Validator
{
delegate REFUNDDENIALREASONS validationHandler(BatchRefund refundToValidate);
public static List<REFUNDDENIALREASONS> ValidateRefund(BatchRefund refundToValidate)
{
List<Delegate> Validations = new List<Delegate>();
List<REFUNDDENIALREASONS> DenialReasons = new List<REFUNDDENIALREASONS>();
Validations = new List<Delegate>();
validationHandler blockHandler = ValidateBlocks;
Validations.Add(blockHandler);
validationHandler accountHandler = ValidateCustomerAccountStatus;
Validations.Add(accountHandler);
foreach (validationHandler v in Validations)
{
DenialReasons.Add(v(refundToValidate));
}
return DenialReasons;
}
public static REFUNDDENIALREASONS ValidateCustomerAccountStatus(BatchRefund refundToHandle)
{
REFUNDDENIALREASONS denialReason;
switch (refundToHandle.RefundCustomer.CustStatus)
{
case "C":
denialReason = REFUNDDENIALREASONS.None;
break;
case "Y":
denialReason = REFUNDDENIALREASONS.AccounthasrecentChargebackNSF;
break;
default:
denialReason = REFUNDDENIALREASONS.Fraud;
break;
}
return denialReason;
}
public static REFUNDDENIALREASONS ValidateBlocks(BatchRefund refundToHandle)
{
List<CustomerBlock> blocks = refundToHandle.RefundCustomer.Blocks;
//add new codes to block here
string[] illegalblockcodes = new string[] { "L1", "C1" };
foreach (string code in illegalblockcodes)
if (blocks.Exists(b => b.BkClassCode == code))
{
return REFUNDDENIALREASONS.Fraud;
}
return REFUNDDENIALREASONS.None;
}
}
You're basically describing a tweak on the Chain-of-responsibility design pattern. There are advantages and disadvantages to this, but it is a good option if you want the flexibility of adding other operations onto your queue at any point in time.
Not necessarily a bad idea. Do you intend to keep track of which validation failed? If you're using a static method that runs it through a queue how are you going to tell?

Lock in properties, good approach?

In my multithreading application I am using some variables that can be altered by many instances in the same time. It is weird but it has worked fine without any problem..but of course I need to make it thread-safe. I am just beginning with locks so I would appretiate your advice:
When client connects, class Client is created where each Client has its own "A" variable.
Sometimes, Client calls method like that:
Client selectedClient SelectOtherClientClassByID(sentID);
selectedClient.A=5;
No problems until now with that even when 5 classes were doing at the same time (threadpool), but I was thinking what about adding locks to A properties?
Like:
A {
get { return mA; }
set {
// use lock here for settting A to some value
}
}
Would it be OK?
You need to use locks in BOTH get and set. This lock must be the same object. For example:
private object mylock = new object();
public int A {
get {
int result;
lock(mylock) {
result = mA;
}
return result;
}
set {
lock(mylock) {
mA = value;
}
}
}
Locking access to properties inside of accessors may lead to bogus results. For the example, look at the following code:
class C {
private object mylock = new object();
public int A {
get {
int result;
lock(mylock) {
result = mA;
}
return result;
}
set {
lock(mylock) {
mA = value;
}
}
}
}
C obj = new C;
C.A++;
(yes, I've copied it from the first answer)
There is a race condition here! Operation "C.A++" actually requires two separate accesses to A, one to get the value and the other to set the updated value. Nothing ensures that these two accesses will be carried out as together without context switch between them. Classical scenario for race condition!
So, beware! It's not a good idea to put locks inside accessors, locks should be explicitly obtained, like the previous answer suggests (though it doesn't have to be with SyncRoots, any object will do)
It's very rare when all you need is just set a single property. More often selectedClient.A = 5 will be a part of a much bigger logical operation, which involves several assignments/evaluations/etc. During that whole operation you'd rather prefer selectedClient to be in a consistent state and not to introduce deadlocks/race conditions. Therefore, it will be much better to expose SyncRoot property in your Client class and lock on that from the calling code:
Client selectedClient = GetClient(...);
lock(selectedClient.SyncRoot)
{
selectedClient.A = 5;
selectedClient.B = selectedClient.A * 54;
}

Categories

Resources