Trying to run methods after api starts up

So I’ve written an api on ASP.Net-Core and I want to run some csvReader methods as soon as the server starts. Currently it just starts up and doesn’t run my DataMigrationController.

class Program
{
    public const string _path =
        "C://path";

    static void Main(string[] args)
    {
        
        CreateWebHostBuilder(args)
            .UseUrls("https://localhost:44301/")
            .Build()
            .Run();

        DataMigrationController DMC = new DataMigrationController();
        DMC.readCSV(_path);
        Console.WriteLine("Done");
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

From the docs, it appears as if the Run() method is blocking; you would want to use Start() instead.

Method 2

You can do this with hangfire.

You can set a job that will be performed only once after starting the app. See Fire-and-forget jobs in hangfire documentation.

Just be careful not to add too many job clone to the queue. You can easily avoid this by using the WorkerCount option. For more info look:
https://docs.hangfire.io/en/latest/background-processing/configuring-degree-of-parallelism.html


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x