How to create an asynchronous method

前端 未结 8 2097
离开以前
离开以前 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:48

    In Asp.Net I use a lot of static methods for jobs to be done. If its simply a job where I need no response or status, I do something simple like below. As you can see I can choose to call either ResizeImages or ResizeImagesAsync depending if I want to wait for it to finish or not

    Code explanation: I use http://imageresizing.net/ to resize/crop images and the method SaveBlobPng is to store the images to Azure (cloud) but since that is irrelevant for this demo I didn't include that code. Its a good example of time consuming tasks though

    private delegate void ResizeImagesDelegate(string tempuri, Dictionary<string, string> versions);
    private static void ResizeImagesAsync(string tempuri, Dictionary<string, string> versions)
    {
        ResizeImagesDelegate worker = new ResizeImagesDelegate(ResizeImages);
        worker.BeginInvoke(tempuri, versions, deletetemp, null, null);
    }
    private static void ResizeImages(string tempuri, Dictionary<string, string> versions)
    {
        //the job, whatever it might be
        foreach (var item in versions)
        {
            var image = ImageBuilder.Current.Build(tempuri, new ResizeSettings(item.Value));
            SaveBlobPng(image, item.Key);
            image.Dispose();
        }
    }
    

    Or going for threading so you dont have to bother with Delegates

    private static void ResizeImagesAsync(string tempuri, Dictionary<string, string> versions)
    {
        Thread t = new Thread (() => ResizeImages(tempuri, versions, null, null));
        t.Start(); 
    }
    
    0 讨论(0)
  • 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"); } );
    
    0 讨论(0)
提交回复
热议问题