Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a DLL which does a time consuming task?

Tags:

c#

enter image description here

In my WPF application, I have to communicate to a datastor over the serial port. I want to separate this communication into a class library for simplicity.

In my DLL, I will be issuing a command to the datastor and wait for 10 seconds to receive the response back. Once I get the response from the datastor, I compile the data to meaningful info and pass to the main application.

My question is how to make the main application to pause for a while to get the data from the external dll and then continue the processing with the data from the dll?

I use .net 4.0

like image 890
sony Avatar asked Jan 27 '26 19:01

sony


2 Answers

Consider calling the DLL method in a new thread

Thread dllExecthread = new Thread(dllMethodToExecute);

and providing a callback from the main program to the dll which can be executed when complete (This prevents locking on the GUI).

edit: Or for simplicities sake if you just want the main program to wait for the DLL to finish execution subsequently call:

dllExecthread.Join();
like image 189
MarcF Avatar answered Jan 30 '26 09:01

MarcF


Maybe you could go with TPL:

        //this will call your method in background
        var task = Task.Factory.StartNew(() => yourDll.YourMethodThatDoesCommunication());

        //setup delegate to invoke when the background task completes
        task.ContinueWith(t =>
            {
                //this will execute when the background task has completed
                if (t.IsFaulted)
                {

                    //somehow handle exception in t.Exception
                    return;
                }          


                var result = t.Result;
                //process result
            });
like image 39
Jurica Smircic Avatar answered Jan 30 '26 07:01

Jurica Smircic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!