I want to call Method2 and then Method1. I know there are multiple ways of doing this like Method1(Method2());
But I just tried the below code.
In the below scenario Method2 is not getting called. So I'm just curious to know where this scenario is useful, why C# has provided this mechanism.
public delegate void Action();
public static void Method1(Action action)
{
}
static void Main()
{
Method1(Method2);
return;
}
public static void Method2()
{
}
You should invoke action within Method1:
...
public static void Method1(Action action)
{
// do not forget to validate input for public methods
if (null == action)
throw new ArgumentNullException("action");
action(); // you should invoke action
}
Related
In case a method takes too long it would make sense to terminate it after a timeout.
Is it possible to implement Method like BreakMyMethod_afterTimeout?
public static void MyMethod()
{
//some code
}
public static async void BreakMyMethod_afterTimeout(int timeoutInSec)
{
//break MyMethod after timeout
}
public static void main()
{
BreakMyMethod_afterTimeout(60); //Is this possible to relize?
MyMethod();
//the program continues here after 60 seconds at the latest
}
I am trying to add webapi (owin.selfhosting) support to existing C# console app and I have problem with callbacks from the controller. Essentially I need to call a function as a reaction to the http request. I think it's possible with delegates/events, but so far no success.
Update:
Using static event seems to work, I used a standard pattern as described in this video (https://www.youtube.com/watch?v=jQgwEsJISy0) and adding a static keyword before event declaration. But mixing static delegate with non static subscriber probably is not the best practice.
Code sample :
//appcontroller.cs
public class AppController : ApiController
{ public delegate void EventHandler(object source, EventArgs args);
public static event EventHandler EventRecived;
protected virtual void OnEventRecived(string arg)
{
if( EventRecived != null)
{
EventRecived(this, arg);
}
}
[Route("api/{arg}")]
public void GetFoo(string arg)
{
/*
*
*/
OnEventRecived();
}
}
//program.cs
class Program
{ static void Main(string[] args)
{ WebApp.Start<Startup>(url: baseAddress);
SomeClass obj = new SomeClass();
AppController.EventHandler+=obj.OnRecivedEvent;
while (true)
{ //do work
}
}
}
class SomeClass
{ public SomeClass() {}
public void OnRecivedEvent(object sender, EventArgs e)
{
Foo(e);
}
public void Foo(string arg)
{
//do something
Console.WriteLine("request of "+arg);
}
}
Example for http get request to http://localhost:8080/api/holy_grail
Console output >>request of holy_grail
We all know about the singleton pattern.
How do you implement a singleton "method"? - a method that is called only once and any other call will do nothing.
I can think a few ways (including Lazy - if (!.IsValueCreated) {... value.method();}) but how would you implement it?
I don't think so there is something like a singleton method.
If you want your method to do execute the block of code only once then you can do that. This can be done in several ways, one of them could be as follows-
public class Foo
{
private static bool _isInitialied;
public void Initialize()
{
if(_isInitialied)
return;
//TODO: Initialization stups.
_isInitialied = true;
}
}
You could achieve this using actions:
public class Test
{
private Action _action;
private void DoSomething()
{
// Do something interesting
_action = DoNothing;
}
private void DoNothing()
{
}
public Test()
{
_action = DoSomething;
}
public void Call()
{
_action();
}
} // eo class Test
I have one class with these three methods. This class is used by many threads.
I would like the Method1 to wait, if Method2 and/or Method3 are running in any threads.
Any suggestions?
public class Class1
{
public static void Method1()
{
Object lockThis = new Object();
lock (lockThis)
{
//Body function
}
}
public static void Method2()
{
//Body function
}
public static void Method3()
{
//Body function
}
}
If I understood correctly, you need something like this:
static object lockMethod2 = new object();
static object lockMethod3 = new object();
public static void Method1()
{
lock (lockMethod2)
lock (lockMethod3)
{
//Body function
}
}
public static void Method2()
{
lock (lockMethod2)
{
//Body function
}
}
public static void Method3()
{
lock (lockMethod3)
{
//Body function
}
}
This allows method3 to execute if method2 is running and vice versa, while method1 must wait for both. Of course, method2 and 3 will not run while 1 is running.
The current implementation of your lock is completely useless, because every thread will lock on a different object.
Locking is usually done with a readonly field that is initialized only once.
Like this, you can easily lock multiple methods:
public class Class1
{
private static readonly object _syncRoot = new object();
public static void Method1()
{
lock (_syncRoot)
{
//Body function
}
}
public static void Method2()
{
lock (_syncRoot)
{
//Body function
}
}
public static void Method3()
{
lock (_syncRoot)
{
//Body function
}
}
}
I would suggest a ReaderWriterLockSlim (http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx)
Similar to read operations, Method 2 and Method3 may occur in parallel, while Method1 (like a write operation) would need to wait for those to finish.
It's not the regular read/write concurrency situation, but the logic is similar.
public class Class1
{
private ReaderWriterLockSlim methodLock = new ReaderWriterLockSlim();
public static void Method1()
{
methodLock.EnterWriteLock();
try
{
//Body function
}
finally
{
methodLock.ExitWriteLock();
}
}
public static void Method2()
{
methodLock.EnterReadLock();
try
{
//Body function
}
finally
{
methodLock.ExitReadLock();
}
}
public static void Method3()
{
methodLock.EnterReadLock();
try
{
//Body function
}
finally
{
methodLock.ExitReadLock();
}
}
}
If you are multi-threading then the lock has to be accessible to all threads. Therefore, in this case, your locks needs to be static for the static methods to see it.
Your current setup will make a new lock object for each thread. Therefore, providing now synchronization.
I want to pass a method ( of void return type and with no input arguments) as parameter using C#. Below is my sample code. How can I do it ?
public void Method1()
{
... do something
}
public int Method2()
{
... do something
}
public void RunTheMethod([Method Name passed in here] myMethodName)
{
myMethodName();
... do more stuff
}
System.Action will fit the bill:
http://msdn.microsoft.com/en-us/library/system.action.aspx
You've also got various generic versions of Action for methods that have parameters but have a void return type, and Func for methods that return something.
So your RunTheMethod method would look like
public void RunTheMethod(Action myMethod)
{
myMethod();
}
Then you can call it with:
RunTheMethod(Method1);
RunTheMethod(Method2);
As mentioned before, you can use delegates – in your case, you could use System.Action to do exactly that.
public void RunTheMethod(System.Action myMethodName)
{
myMethodName();
... do more stuff
}
Take a look at delegates which act like a pointer to a method
You should look at Delegates to get a solution to your query. They basically serve as a pointer or reference to a function.
Also take a look at this example for a better understanding.
//Delegate
public delegate void OnDoStuff();
class Program
{
static void Main(string[] args)
{
//Pass any of the method name here
Invoker(Method1);
Console.ReadLine();
}
private static void Invoker(OnDoStuff method)
{
method.Invoke();
}
private static void Method1()
{
Console.WriteLine("Method1 from method " + i);
}
private static void Method2()
{
Console.WriteLine("Method2 from method " + i);
}
private static void Method3()
{
Console.WriteLine("Method3 from method " + i);
}
}