How to create an asynchronous method

前端 未结 8 2235
离开以前
离开以前 2020-12-22 20:18

I have simple method in my C# app, it picks file from FTP server and parses it and stores the data in DB. I want it to be asynchronous, so that user perform other operations

8条回答
  •  臣服心动
    2020-12-22 20:54

    try this method

    public static void RunAsynchronously(Action method, Action callback) {
        ThreadPool.QueueUserWorkItem(_ =>
        {
            try {
                method();
            } 
            catch (ThreadAbortException) { /* dont report on this */ } 
            catch (Exception ex) {
            }
            // note: this will not be called if the thread is aborted
            if (callback!= null) callback();
        });
    }
    

    Usage:

    RunAsynchronously( () => { picks file from FTP server and parses it}, 
           () => { Console.WriteLine("Parsing is done"); } );
    

提交回复
热议问题