One of the ways can be with a BackgroundWorker
(you can adapt the MS samples)
How to avoid blocking UI thread while waiting for a long-running operation to finish
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!
1 answer
Sort by: Most helpful
-
Castorix31 81,461 Reputation points
2021-10-08T18:37:41.66+00:00