Multithreading: C# program running C dll - Unresponsive C#
I wrote a C dll that performs two tasks:
1) Relay certain messages to the C# program
2) Perform an intensive task on a different thread
It all works but the C# UI is unresponsive, even though C is running the intensive task on a different thread.
I have also exposed the C function that kicks off the intensive task to C#, allowing C# to attempt to run that function on a different thread.
No matter 开发者_高级运维what, C# gets bogged down and the C# program becomes unresponsive when the intensive task runs.
I forgot to mention that I have written the entire program in C and it works without a problem but I'd like to write a C# library to use this in future .NET projects.
[DllImport(@"C:\projects\math\randomout\Debug\randout.dll", CharSet = CharSet.Auto, EntryPoint = "task_ToggleTask")]
internal static extern bool task_ToggleTask();
__declspec( dllexport ) BOOL task_ToggleTask()
{
if ( _threadStopped )
{
_threadStopped = FALSE;
_t_TaskHandle = ( HANDLE )_beginthread( task_Calculate, 0, NULL );
return TRUE;
}
else
{
_threadStopped = TRUE;
CloseHandle( _t_TaskHandle );
return FALSE;
}
}
static void task_Calculate( void* params )
{
while ( !_threadStopped )
{
WORD nextRestInterval = rand_GetBetween( 15, 50 );
/*
trivial math calculations here...
*/
//next update is at a random interval > 0ms
Sleep( nextRestInterval );
}
_endthread();
}
You need to reduce your thread's priority. I'm assuming though this happens to your system and not just the program. If it happens in your program, are you certain nothing else is going on in your main app thread and that its actually running on a separate thread?
Try reducing the thread's priority - see: Programmatically limit CPU Usage of a Thread running inside a Service
I'll try a general answer, since you haven't specified which C# UI technology you're using (WPF or Winforms), and haven't given any example of your UI code:
I think you'd better off keep your C code as a simple utility library, without trying to do any threading stuff there, and Let the C# code manage the background thread. .Net UI has many threading techniques to keep the UI responsive while doing some long tasks in the background, e.g.: Backgroundworker
, Dispatcher.Invoke
, Control.Invoke
etc... (take a look at this question for example).
精彩评论