How to avoid blocking UI thread while waiting for a long-running operation to finish

bioan 41 Reputation points
2021-10-08T14:20:42.05+00:00

Hi!

In my C# library I need to use a function imported from a C++ dll file using P/Invoke mechanism. This function is a long-time running operation (usually takes more than a minute per calling). For using the C++ function, a callback function is also indicated. With the great help from the forum (thanks to RLWA32-6355 user) the C# conversion of both are like below:

 [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
 delegate uint CSCALLBACK([MarshalAs(UnmanagedType.IUnknown)] object document, IntPtr context, double progress);

 [DllImport("ArrayMarshal.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
 static extern int Longtime_function([MarshalAs(UnmanagedType.IUnknown)] object document, CSCALLBACK cbFunc, IntPtr context);

Now I have to understand how to deal with this callback inside my C# library, because I want to wait the result from Longtime_function() to use immediately when is available but in the same time I do not want this Longtime_function() waiting to block my current app interface.
Longtime_function() reads some data in a for loop, and after the parsing is finished it must writes a temporary file on my disk which will be converted into another final file, like below:

void ConversionUtility()
 {
     string myTempFile = "D:\\Temp";
     for (int i = 0; i < 20; i++)
     {
         Longtime_function(i);//here a temporary file (tempFile) is created on disk at each iteration of the for cycle
         // OtherLongtime_function must wait for Longtime_function() to finish parsing internal data and write the file (tempFile) to the disk
         string ConvertedFilePath = myTempFile + i.ToString();
         OtherLongtime_function(tempFile, ConvertedFilePath);
     }
 }

How can I use in this scenario the callback function provided by the C++ library?
There are some other API like async which can be used in this case?
I have never use asynchronous technology before, but as I read, something like Task class is very popular.
Ideally ConversionUtility() must run on a different thread than the main app thread.

Thanks for any feedback!

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,198 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,520 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Castorix31 81,461 Reputation points
    2021-10-08T18:37:41.66+00:00

    One of the ways can be with a BackgroundWorker
    (you can adapt the MS samples)

    0 comments No comments