Let's assume that we have got simple program like below. Is it even possible to make some action on unexpected quit of the program?
static void Main(string[] args)
{
}
public void onKillDoSomething()
{
...
}
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'm currently writing a C# console application and would like to give the user the ability to chose what feature to be executed. For example, when I start MyApp.exe -help the help should show, or when I start MyApp.exe -shutdown the computer should shutdown. How do I pass/check that?
My current code doesn't seem to work:
static void Main(string[] args)
{
if (args.Equals("-help"))
{
Console.WriteLine("Some help here...");
}
}
static void Main(string[] args)
{
ProcesArguments(args);
}
static void ProcesArguments(string[] parameters)
{
foreach (var parameter in parameters)
{
switch (parameter.ToLower())
{
case "-help":
DisplayHelp();
break;
case "-reboot":
RebootComputer();
break;
}
}
}
static void DisplayHelp()
{
Console.WriteLine($"Syntax: {System.AppDomain.CurrentDomain.FriendlyName} <Parameter>");
// ...
}
static void RebootComputer()
{
// ...
}
Args is an array, so you have to reference the argument by its index. So args[0] corresponds to the first argument passed in. In addition, check the array length first to ensure an argument was even provided before you try to access it.
static void Main(string[] args)
{
if (args.Length > 0 && args[0] == "-help")
{
Console.WriteLine("Some help here...");
}
}
args is an array so you need to look for -help occurrence in it. You can achieve it using String.Contains() method.
static void Main(string[] args)
{
if (args.Contains("-help"))
{
Console.WriteLine("Some help here...");
}
}
As per this post, the top voted answer suggested that we can use async directly in main. Or I misunderstood it?
Can't specify the 'async' modifier on the 'Main' method of a console app
My main class:
public class Program
{
public static async Task Main(string[] args)
{
ApproveEvents ap = new ApproveEvents();
List<MyModel> result = new List<MyModel>();
result = await ap.ApproveAsync();
if (result.count > 0)
{
//do something here
}
}
}
And,
public class ApproveEvents
{
public async Task<List<MyModel>> ApproveAsync()
{
//blah blah
}
}
Visual Studio 2017 is complaining about no Main method for an entry point.
How should I resolve this?
async Task Main is available in C# 7.1. You can change it in build properties (the default is the latest major version, which is 7.0)
i'd recommend you looking at this topic to help you, it speaks right into your issue.
it stated:
As I showed above, if you want to await an async operation in the
entrypoint method, you need to apply some workaround, because the
following entrypoint definition is invalid:
public static async Task Main(string[] args)
{
await BuildWebHost(args).RunAsync();
}
in order to make this work you will need to do the following workaroung:
public static void Main(string[] args)
{
BuildWebHost(args).RunAsync().GetAwaiter().GetResult();
}
or calling wait() on the task object itself:
public static void Main(string[] args)
{
BuildWebHost(args).RunAsync().Wait();
}
there is a list of valid entry points in C# 7.1, this is the up to date list:
public static void Main();
public static int Main();
public static void Main(string[] args);
public static int Main(string[] args);
public static Task Main();
public static Task<int> Main();
public static Task Main(string[] args);
public static Task<int> Main(string[] args);
In C# , in Visual Studio, using a Console Application, is there a way to make methods in a class and call them in main program using readline?
Aka, a way to choose which methods to open when the program is running.
Easiest way is a switch statement for <4 cases, and a Dictionary for 4 or more cases.
class Program
{
private static IDictionary<string, Action> MethodMappings = new Dictionary<string, Action> {
{"Method1", Method1},
{"Method2", Method2},
...
}
public static void Main(string[] args) {
var methodCall = Console.ReadLine();
if (!MethodMappings.ContainsKey(methodCall)) {
//unrecognized command
}
MethodMappings[methodCall].Invoke();
}
private static void Method1() { ... }
private static void Method2() { ... }
}
This is very much possible using Reflection. Here is sample code to help you out:
class Program
{
public static void Hello1()
{
Console.WriteLine("\nHello 1");
}
public static void Hello2()
{
Console.WriteLine("\nHello 2");
}
static void Main(string[] args)
{
while (true)
{
String method = Console.ReadLine();
Type methodType = typeof(Program);
MethodInfo voidMethodInfo = methodType.GetMethod(method);
voidMethodInfo.Invoke(method,null);
}
}
}
For more information you can visit here.
I want to launch 2 or more webApp. How do I do that in .NET? I am newby to C# and .NET.
class Program
{
static void Main(string[] args)
{
launchService("localhost:4234");
launchService("localhost:4265");
}
public static void launchService(Component component)
{
using (WebApp.Start<Startup>(component.Url()))
{
Console.WriteLine("Running on {0}", component.Url());
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
}
}
This should be some thing as below:
class Program
{
static IDisposable app1;
static IDisposable app2;
static void Main(string[] args)
{
launchServices("http://localhost:4234", "http://localhost:4265");
Console.ReadLine();
app1.Dispose();
app2.Dispose();
}
public static void launchServices(string url1, string url2)
{
app1 = WebApp.Start<StartupApp1>(url1);
app2 = WebApp.Start<StartupApp2>(url2);
}
}
Following links may help you further:
http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api
OWIN cannot run multiple apps in isolation using webapp.start
Note: There may be some compilation errors/typos in above code as I have just typed it using my IPad.