51

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 on App, once parsing is done he has to get message stating "Parsing is done".

I know it can achieved through asynchronous method call but I dont know how to do that can anybody help me please??

default
  • 11,485
  • 9
  • 66
  • 102
Prashant Cholachagudda
  • 13,012
  • 23
  • 97
  • 162

8 Answers8

74

You need to use delegates and the BeginInvoke method that they contain to run another method asynchronously. A the end of the method being run by the delegate, you can notify the user. For example:

class MyClass
{
    private delegate void SomeFunctionDelegate(int param1, bool param2);
    private SomeFunctionDelegate sfd;

    public MyClass()
    {
        sfd = new SomeFunctionDelegate(this.SomeFunction);
    }

    private void SomeFunction(int param1, bool param2)
    {
        // Do stuff

        // Notify user
    }

    public void GetData()
    {
        // Do stuff

        sfd.BeginInvoke(34, true, null, null);
    }
}

Read up at http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx

Callum Rogers
  • 15,630
  • 17
  • 67
  • 90
  • 18
    Note that rather than declaring and using a `SomeFunctionDelegate` you can just use a `Action` and similarly a `Func` for methods that are not void. – Callum Rogers Nov 24 '10 at 10:10
  • 2
    new Action(MethodName).BeginInvoke(1, "text", null, null); – net_prog Oct 12 '11 at 11:29
  • **this is Asynchronous delegates and not asynchronous methods**.Asynchronous methods follow a similar protocol outwardly, but they exist to solve a much more difficult problem – Royi Namir Feb 26 '13 at 13:42
  • @Royi: I think you are confused, this answer is nearly 4 years old and was before the time of `async` and such so is appropriate for the question. – Callum Rogers Feb 26 '13 at 16:45
  • @CallumRogers No I'm not. You are. read this http://i.stack.imgur.com/i3pH2.jpg and then this http://i.stack.imgur.com/BcX33.jpg they all taken from c# book from joe albahari v4. ( Fw4 , and has nothing to do with asunc) they are all from here http://www.albahari.com/threading/#_Asynchronous_delegates). you should Edit your answer. it is not a an asynchrouns method but delegate. – Royi Namir Feb 26 '13 at 18:38
  • @Royi: I see what you mean - however just because the question is asking about asynchronous **methods** does not mean he's referring to the same thing that you are. OP is more requesting a way to *call a method asynchronously* and this is the correct answer. I have to say I've never really seen it called `asynchronous methods` - I think you mean [`asynchronous operation`](http://msdn.microsoft.com/en-us/library/ms734701.aspx) instead. – Callum Rogers Feb 26 '13 at 18:55
  • 1
    You mean "I thought you meant...". they are actually different things.The OP probably don't know that there are 2 subjects. he asked about asynchronous methods and you gave him an answer about Asynchronous delegates. – Royi Namir Feb 26 '13 at 19:16
20

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"); } );
Zain Ali
  • 15,535
  • 14
  • 95
  • 108
6

Any time you're doing something asynchronous, you're using a separate thread, either a new thread, or one taken from the thread pool. This means that anything you do asynchronously has to be very careful about interactions with other threads.

One way to do that is to place the code for the async thread (call it thread "A") along with all of its data into another class (call it class "A"). Make sure that thread "A" only accesses data in class "A". If thread "A" only touches class "A", and no other thread touches class "A"'s data, then there's one less problem:

public class MainClass
{
    private sealed class AsyncClass
    {
        private int _counter;
        private readonly int _maxCount;

        public AsyncClass(int maxCount) { _maxCount = maxCount; }

        public void Run()
        {
            while (_counter++ < _maxCount) { Thread.Sleep(1); }
            CompletionTime = DateTime.Now;
        }

        public DateTime CompletionTime { get; private set; }
    }

    private AsyncClass _asyncInstance;
    public void StartAsync()
    {
        var asyncDoneTime = DateTime.MinValue;
        _asyncInstance = new AsyncClass(10);
        Action asyncAction = _asyncInstance.Run;
        asyncAction.BeginInvoke(
            ar =>
                {
                    asyncAction.EndInvoke(ar);
                    asyncDoneTime = _asyncInstance.CompletionTime;
                }, null);
        Console.WriteLine("Async task ended at {0}", asyncDoneTime);
    }
}

Notice that the only part of AsyncClass that's touched from the outside is its public interface, and the only part of that which is data is CompletionTime. Note that this is only touched after the asynchronous task is complete. This means that nothing else can interfere with the tasks inner workings, and it can't interfere with anything else.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • 2
    That "Async task ended at {0}" string isn't printed after the async task finishes... – Jacob Apr 07 '12 at 02:23
  • 2
    Plz correct your statement "Any time you're doing something asynchronous, you're using a separate thread". It is wrong. Check [Asynchrony in C# 5.0 part Four: It's not magic](http://blogs.msdn.com/b/ericlippert/archive/2010/11/04/asynchrony-in-c-5-0-part-four-it-s-not-magic.aspx) – Gennady Vanin Геннадий Ванин Jan 14 '13 at 06:10
  • It's always a _separate_ thread, logically, even if, physically, the same thread can be reused. – John Saunders Jan 14 '13 at 06:18
4

Here are two links about threading in C#

I'd start to read about the BackgroundWorker class

tanascius
  • 53,078
  • 22
  • 114
  • 136
4

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(); 
}
Fischer
  • 246
  • 1
  • 3
  • 11
1

ThreadPool.QueueUserWorkItem is the quickest way to get a process running on a different thread.

Be aware that UI objects have "thread affinity" and cannot be accessed from any thread other than the one that created them.

So, in addition to checking out the ThreadPool (or using the asynchronous programming model via delegates), you need to check out Dispatchers (wpf) or InvokeRequired (winforms).

  • If anyone does need to access UI elements created on another thread (cross-thread exceptions), see this great post: http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the-t – Callum Rogers Jul 21 '09 at 14:11
0

In the end you will have to use some sort of threading. The way it basically works is that you start a function with a new thread and it will run until the end of the function.

If you are using Windows Forms then a nice wrapper that they have for this is call the Background Worker. It allows you to work in the background with out locking up the UI form and even provides a way to communicate with the forms and provide progress update events.

Background Worker

QueueHammer
  • 10,515
  • 12
  • 67
  • 91
0

.NET got new keyword async for asonchrynous functions. You can start digging at learn.microsoft.com (async). The shortest general howto make function asonchrynous is to change function F:

Object F(Object args)
{
    ...
    return RESULT;
}

to something like this:

async Task<Object> FAsync(Object args)
{
    ...
    await RESULT_FROM_PROMISE;
    ...
    return RESULT;
}

The most important thing in above code is that when your code approach await keyword it return control to function that called FAsync and make other computation until promissed value has been returned and procede with rest of code in function FAsync.

Piotr Wojcik
  • 95
  • 1
  • 17