How to achieve WNetAddConnection2 equivalent with timeout?

The next call to WNetAddConnection2 seems to last forever. Please note that the name of the machine is intentionally wrong - I would like it to end quickly and not be blocked 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"); } } } 
+4
source share
1 answer

In earlier versions of Windows, it was not possible to terminate a process that was stuck in one of the WNetAddConnection functions. This has been fixed in Vista. According to Larry Osterman , the fix is CancelSynchronousIo .

The solution to your problem:

  • Run a new thread to start WNetAddConnection2
  • Set a timer or wait in an existing thread.
  • After a timeout call, CancelSynchronousIo indicates the handle to the connection thread.

I can't think of any reason why this interacts poorly with .Net, but I haven't really tried ...

+1
source

Source: https://habr.com/ru/post/1396963/


All Articles