以下对 WNetAddConnection2 的调用似乎永远无法完成。请注意,机器名称是故意错误的 - 我希望它能快速失败而不是永久阻塞。有没有一种方法实现类似的功能但带有超时?
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");
}
}
}
ManualResetEvent
)以在WaitOne
上设置超时,然后(采用粗暴的方式)使用Thread.Abort
终止线程。 - M.BabcockThread.Abort
是不必要的,因为它无法中止连接尝试。 - Gabe