c# - 如何实现与 WNetAddConnection2 相同的超时?

标签 c# windows winapi networking

以下对 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");
        }
    }
}

最佳答案

在早期版本的 Windows 上,无法终止卡在 WNetAddConnection 函数之一中的进程。这在 Vista 中已修复。 According to Larry Osterman , 修复是 CancelSynchronousIo功能。

您的问题的解决方案是:

  1. 启动一个新线程来运行 WNetAddConnection2
  2. 设置计时器或在现有线程中等待。
  3. 超时后调用 CancelSynchronousIo 指定连接线程的句柄。

我想不出有什么原因会导致它与 .Net 交互不良,但我还没有真正尝试过...

关于c# - 如何实现与 WNetAddConnection2 相同的超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9323023/

相关文章:

sql-server - 我应该将我的电子邮件内容存储在数据库或文件系统中的什么位置?

python - 如何让 bjam 检测我在 Windows 上安装的 Python?

windows - 如果 Steam 可以映射 Xbox 360 Controller 上的指南按钮,为什么我不能

c# - IQueryable 的结构是什么?

c# - 如何使用 IFileOperation?

c# - 通过从 C# 应用程序获取 DBName 创建 DB

c# - 鼠标悬停文本框时删除浅蓝色边框

windows - Win8 是否也为遗留应用程序添加了内置拼写检查器?

windows - 资源管理器集成在上下文菜单中,但使用已经运行的实例

c++ - WIN32 : Need Help With stdout Redirect on Hybrid Console + GUI App