简体   繁体   中英

How to achieve the equivalent of WNetAddConnection2 with a timeout?

The following call to WNetAddConnection2 seems to hang forever. Note that the machine name is intentionally wrong - I'd like this to fail fast rather than block forever. Is there a way to achieve similar functionality but with a timeout?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [StructLayout(LayoutKind.Sequential)]
        public class NETRESOURCE
        {
            public int dwScope;
            public int dwType;
            public int dwDisplayType;
            public int dwUsage;
            public string LocalName;
            public string RemoteName;
            public string Comment;
            public string Provider;
        }
        [DllImport("mpr.dll")]
        public static extern int WNetAddConnection2(NETRESOURCE netResource, string password, string username, int flags);

        private void Form1_Load(object sender, EventArgs e)
        {
            NETRESOURCE myResource = new NETRESOURCE();
            myResource.dwScope = 0;
            myResource.dwType = 0; //RESOURCETYPE_ANY
            myResource.dwDisplayType = 0;
            myResource.LocalName = "";
            myResource.RemoteName = @"\\invalid.machine.com";
            myResource.dwUsage = 0;
            myResource.Comment = "";
            myResource.Provider = "";

            int returnValue = WNetAddConnection2(myResource, "password", "username", 0); //hangs forever
            Debug.Print("Finished connecting");
        }
    }
}

On earlier versions of Windows it was impossible to terminate a process that was stuck in one of the WNetAddConnection functions. This was fixed in Vista. According to Larry Osterman , the fix is the CancelSynchronousIo function.

The solution to your problem is:

  1. Start a new thread to run WNetAddConnection2
  2. Set a timer or wait in your existing thread.
  3. After the timeout call CancelSynchronousIo specifying the handle of the connection thread.

I can't think of any reason why this would interact badly with .Net, but I haven't actually tried it...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM