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);
Related
class Program
{
static void Main(string[] args)
{
//I want to call the bird method here
}
public void bird(Program program)
{
birdSpeech();
}
public void birdSpeech()
{
Console.WriteLine("Chirp Chirp");
}
}
How do I call bird in the main, I also tried to call the method from a object of the class but that didn't work
Does it even make sense to do this (I try to avoid static methods as much as possible).
If a method can be made static without changing the code, you should make it static. To answer your question though, you can create an instance of Program in your Main function and call the non-static methods through it.
class Program
{
static void Main(string[] args)
{
var p = new Program();
p.bird();
}
public void bird()
{
birdSpeech();
}
public void birdSpeech()
{
Console.WriteLine("Chirp Chirp");
}
}
Could do something like this
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var p = new Program();
p.bird(p);
}
public void bird(Program program)
{
birdSpeech();
}
public void birdSpeech()
{
Console.WriteLine("Chirp Chirp");
}
}
I have some code that is using a third-party library that I can't bypass. This library provides some auxiliary features that I need. At this time, my code is setup like this:
static Engine engine = new Engine();
static void Main(string[] args)
{
engine.Execute(MyCode);
}
private static void MyCode()
{
// my code goes here
}
Here's my challenge: I have to instantiate some code before MyCode can use it because that instantiation must hit a database and takes longer than the threshold allowed by Engine. I can't use a static variable because multiple instances will be necessary. Which basically means, I want something like this:
static Engine engine = new Engine();
static void Main(string[] args)
{
MyClass c = new MyClass();
c.Initialize(); // This is the db call
engine.Execute(MyCode); // This line is the problem
}
private static void MyCode(MyClass c)
{
// my code goes here
c.DoStuff();
}
My problem is, I basically need to create an overloaded method that takes a parameter. However, the Execute method in the third-party library doesn't let me do that. Is there some C# syntactial way I can do this that I'm missing?
You're looking for lambda expressions:
engine.Execute(() => MyCode(c));
I'm assuming that Engine.Execute takes an instance of Action.
You could make the MyCode function an instance member function on MyClass, then pass MyClass.MyCode to Engine.Execute as an Action.
public class Engine
{
public void Execute(Action action)
{
action.Invoke();
}
}
public class MyClass
{
public void Initialize()
{
System.Threading.Thread.Sleep(500); //Simulate some work.
}
public void Run()
{
// I've renamed it from MyCode to Run, but this method is essentially your
// my code method.
Console.WriteLine($"I'm being run from the engine! My Id is {_id}.");
}
private readonly Guid _id = Guid.NewGuid();
}
public static class Program
{
static void Main(string[] args)
{
var engine = new Engine();
var c = new MyClass();
c.Initialize();
engine.Execute(c.Run);
}
}
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.
How CLR knows which method to call since they are returning different value(One is void and another is int) ? In sense of Overloading this is also not right, a method with same parameter with different return type.
example:
class Program
{
static int Main(String[] args) //Main with int return type but Parameter String[] args
{
return 0;
}
/* this main method also gonna get called by CLR even though return type void and Same parameter String[] args.
static void Main(String[] args) //Main with int return type but String[] args
{
} */
private static void func(int one)
{
Console.WriteLine(one);
}
private static int func(int one) //compiler error. two overloaded method cant have same parameter and different return type.
{
return 1;
}
}
but main method is not maintaining overloading rules.
in .NET, an executable can have only one entry point i.e. only one Main method is allowed. To be more specific, the Main method is considered as an entry point only if the sigature matches any of the below 2 and the method is static.
Main(String[])
Main()
If, you provide a main method whose signature is different from above two, it is not considered as Main method. So, below code is allowed,
class Program
{
static void Main () //Entry point
{
}
static void Main(int number)
{
}
}
The below code doesn't compile because, it finds matching signature at two places.
class Program
{
static void Main () //Entry point
{
}
static void Main(String[] args) //another entrypoint!!! Compile Error
{
}
}
Below code also doesn't compile because there is no entry point at all,
class Program
{
static void Main (int a) //Not an Entry point
{
}
static void Main(float b) //Not an entry point
{
}
}
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.