private void InitializeSession()

in sources/Google.Solutions.Ssh/Native/Libssh2Session.cs [101:173]


        private void InitializeSession(bool force)
        {
            using (SshTraceSource.Log.TraceMethod().WithParameters(force))
            {
                if (this.sessionHandle != null && force)
                {
                    //
                    // Close existing session to force re-initialization.
                    //
                    this.sessionHandle.CheckCurrentThreadOwnsHandle();
                    this.sessionHandle.Dispose();
                    this.sessionHandle = null;
                }

                if (this.sessionHandle == null)
                {
                    this.sessionHandle = NativeMethods.libssh2_session_init_ex(
                        Alloc,
                        Free,
                        Realloc,
                        IntPtr.Zero);

                    if (this.traceHandlerDelegate != null)
                    {
                        //
                        // NB. We must not pass an anonymous delegate to
                        // libssh2_trace_sethandler as it might be garbage-
                        // collected while still being referenced by native
                        // code.
                        //

                        NativeMethods.libssh2_trace_sethandler(
                            this.sessionHandle,
                            IntPtr.Zero,
                            this.traceHandlerDelegate);

                        NativeMethods.libssh2_trace(
                            this.sessionHandle,
                            this.traceMask);
                    }

                    NativeMethods.libssh2_session_set_timeout(
                        this.sessionHandle,
                        (int)this.timeout.TotalMilliseconds);

                    NativeMethods.libssh2_session_set_blocking(
                        this.sessionHandle,
                        this.blocking ? 1 : 0);

                    if (this.Banner != null)
                    {
                        _ = NativeMethods.libssh2_session_banner_set(
                            this.sessionHandle,
                            BannerPrefix + this.Banner);
                    }

                    foreach (var preferredMethod in this.preferredMethods)
                    {
                        var prefs = string.Join(",", preferredMethod.Value);
                        var result = (LIBSSH2_ERROR)NativeMethods.libssh2_session_method_pref(
                            this.sessionHandle,
                            preferredMethod.Key,
                            prefs);
                        if (result != LIBSSH2_ERROR.NONE)
                        {
                            throw CreateException(result);
                        }
                    }
                }

                Debug.Assert(this.sessionHandle != null);
            }
        }