runtime icon indicating copy to clipboard operation
runtime copied to clipboard

.Net Core 2.0 DllImport not working in Linux

Open steveharter opened this issue 8 years ago • 3 comments

copied from https://github.com/dotnet/core-setup/issues/3566 authored by @ms0713

Steps to reproduce

@martinwoodward What is the alternative for following code: This code i m using in Windows. I want alternate code for Linux(RHEL7).

usingSystem.Runtime.InteropServices;
namespace PInvokeSamples {
    public static class Program {
        // Import the kernel32.dll and define the method corresponding to the native function.
        [DllImport("kernel32.dll")]
        private static extern uint GetCurrentThreadId();

        public static void Main(string[] args){
            // Invoke the function and get the process Thread ID.
            uint tid = GetCurrentThreadId();
            Console.WriteLine(tid);
        }
    }
}

Expected behavior

It should work on Linux(RHEL7)

Actual behavior

It is not working in Linux(RHEL7)

Environment data

It is working fine on windows machine.

steveharter avatar Jan 04 '18 20:01 steveharter

@ms0713 Your example calls the underlying OS API. It does not work on Unix because of kernel32.dll and GetCurrentThreadId are Windows specific.

There is no direct equivalent of Windows 32-bit thread id on Unix. The right answer to your question depends on what you are using the thread id for.

If you just need an arbitrary 32-bit thread id, you can use Environment.CurrentManagedThreadId. This .NET API works fine on all platforms.

jkotas avatar Jan 04 '18 21:01 jkotas

@jkotas, @steveharter I want to bind a processor core to particular thread. Thats why I need native thread id so that I can set the Thread Affinity. There should be a mechanism to do this in .Net Core. In windows, kernel32.dll is there to get the native thread id. There must be similar way in Linux also to get the native thrad id i.e. libc.so.6.

If there is any other alternate way for setting Thread Affinity that also works on Linux then do suggest me.

Also I would like to reopen this issue.

ms0713 avatar Jan 05 '18 03:01 ms0713

bind a processor core to particular thread

Here is an example on how to do this on Linux: https://stackoverflow.com/questions/15687342/set-processor-affinity-for-current-thread-on-mono-linux/17124433#17124433

There should be a mechanism to do this in .Net Core.

https://github.com/dotnet/corefx/issues/18924 is a proposal to add portable API for setting thread affinity to .NET Core.

jkotas avatar Jan 05 '18 04:01 jkotas