加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何通过超时实现WNetAddConnection2的等效?

发布时间:2020-12-15 21:30:55 所属栏目:百科 来源:网络整理
导读:以下对WNetAddConnection2的调用似乎永远挂起.请注意,机器名称是故意错误的 – 我希望快速失败而不是永久阻止.有没有办法实现类似的功能但超时? using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using Syste
以下对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功能.

您的问题的解决方案是:

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

我想不出有什么原因会与.Net发生严重的互动,但我还没有尝试过……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读