views:

2020

answers:

6

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??

+2  A: 

Here are two links about threading in C#

I'd start to read about the BackgroundWorker class

tanascius
Thanks for response ,is it possible to do it without threads, may be with delegates?
Prashant
You can use a BeginInvoke(), but that invokes another thread, too. Really, have a look at the BackgroundWorker - it is easy to use and provides a notify when the job is done.
tanascius
+4  A: 

It's very simple. You create a delegate. Assign your function to it and then you make a async call. This article describe it very well (it also teach you what's a delegate).

Davide Vosti
Link didn't work for me??
Ian Jacobs
Link worked for me.
Callum Rogers
Yeah scratch that, I must be going crazier...
Ian Jacobs
+3  A: 

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
+1 for BeginInvoke
plinth
This was a lifesaver!
Anwar Pinto
A: 

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).

Will
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
+1  A: 

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
A: 

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

JustSmith