在多线程中使用多个AxMsRdpClient7NotSafeForScripting的问题. [英] Problem with using multiple AxMsRdpClient7NotSafeForScripting in multi threads.

查看:461
本文介绍了在多线程中使用多个AxMsRdpClient7NotSafeForScripting的问题.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨.我决定编写自己的多线程rdp客户端.在我的程序编写过程中,我遇到了一个错误-从对COM组件的调用中返回了错误HRESULT E_FAIL.在MSTSCLib.IMsRdpClient7.set_UserName(String pUserName).有人可以帮助我吗?
我的代码段:

Hi. I decide write my own multi thread rdp client. During work of my programm I''ve got an error - Error HRESULT E_FAIL has been returned from a call to a COM component. at MSTSCLib.IMsRdpClient7.set_UserName(String pUserName).Can anybody help me?
My code snippet:

object [] args = new object[5];
args[0] = pathToSuccessHosts;
args[1] = pathToBadHosts;
args[2] = pathToErrors;
args[3] = _countDBRecords;

panelRdpControlContainer.Size = new Size(0, 0); //  container for AxMsRdpClient7NotSafeForScripting elements

 
			
int countThreads = 10;

 for (int i = 0; i < countThreads; i++)
	{  
		Thread th = new Thread(_doRDPConnection.DoRDPConnection);
	   
		th.IsBackground = true;
		th.SetApartmentState(ApartmentState.STA);
		
		AxMSTSCLib.AxMsRdpClient7NotSafeForScripting rdpclient = new AxMSTSCLib.AxMsRdpClient7NotSafeForScripting();
	 
		rdpclient.Name = string.Format("rdpClient{0}", i); 
		rdpclient.OcxState = (System.Windows.Forms.AxHost.State) rdpclient.GetOcx();  
		
		panelRdpControlContainer.Controls.Add(rdpclient); // Add control to System.Windows.Forms.Panel panelRdpControlContainer
	   
		args[4] = rdpclient; 
		
		th.Start(args);
	}
	public class RDPConnection
    {
        Form form1;
        public static volatile int _countThreads;
        public static volatile int _currentLine;
        public static volatile int _countHandledRecords;
        public volatile bool _shouldStop = false;
        public static Object _lockGenRDPFile = new Object();
        public static Object _lockSuccessHostsFile = new Object();
        public static Object _lockBadHostsFile = new Object();
        public static Object _lockErrorsFile = new Object();
        public static Object _lockProgressBar = new Object();
        public static Object _lockRDPClientControl = new Object();
        delegate void SetTextDelegate(string text);
        delegate void SetProgressValueDelegate(int value);
        SetProgressValueDelegate setProgressValueDelegate;
        SetTextDelegate d;

        [DllImport("user32.dll")]
        public static extern bool PostMessage(int hWnd, uint Msg, int wParam, Int64 lParam);

        public DoRDPConnection(Form  form)
        {
            d = SetCountThreads;
            setProgressValueDelegate = SetProgressValue;
            form1 = form;
        }

        public void RequestStop()
        {
            _shouldStop = true;
        } 
         
        public void SetCountThreads(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (form1.lblCountThreads.InvokeRequired)
            {
                form1.lblCountThreads.Invoke(d, new object[] { text });
            }
            else
            {
                form1.lblCountThreads.Text = text;
            }
        }

        public void SetProgressValue(int value)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (form1.progress.InvokeRequired)
            {
                form1.progress.Invoke(setProgressValueDelegate, new object[] { value });
            }
            else
            {
                form1.progress.Value = value;
            }
        }

        
        public void DoRDPConnection(object args)
        {
            try
            {
                bool bOnConnecting = false;
                bool bOnConnected = false;
                bool bOnLoginComplete = false;
                ManualResetEvent mre = new ManualResetEvent(false);
                RDPData rdpData = null;

                Array argArray = new object[3];
                argArray = (Array)args;

                string pathToSuccessHosts = (string)argArray.GetValue(0);
                string pathToBadHosts = (string)argArray.GetValue(1);
                string pathToErrors = (string)argArray.GetValue(2);
                long countDbRecords = (long)argArray.GetValue(3);
                
                AxMSTSCLib.AxMsRdpClient7NotSafeForScripting rdpclient = (AxMSTSCLib.AxMsRdpClient7NotSafeForScripting)argArray.GetValue(4);
                
                _countThreads++;
                SetCountThreads(string.Format("Threads:{0}", _countThreads));

                rdpclient.OnLoginComplete += delegate(object sender, EventArgs e)
                {
                    MessageBox.Show("OnLoginComplete"); 
                    bOnLoginComplete = true;

                    if (rdpData != null)
                    {
                        lock (_lockSuccessHostsFile)
                        {
                            using (StreamWriter w = new StreamWriter(pathToSuccessHosts, true))
                            {
                                w.WriteLine(string.Format("{0}@{1};{2}", rdpData.IP, rdpData.Login, rdpData.Password));
                            }
                        }
                    }
                };

                rdpclient.OnConnecting += delegate(object sender, EventArgs e)
                {
                    //MessageBox.Show("OnConnecting"); 
                    bOnConnecting = true;

                };

                rdpclient.OnDisconnected += delegate(object sender, AxMSTSCLib.IMsTscAxEvents_OnDisconnectedEvent e)
                { 
                    mre.Set();
                };

                rdpclient.OnConnected += delegate(object sender, EventArgs e)
                {
                    //MessageBox.Show("OnConnected");
                    bOnConnected = true;
                };
 
                
                rdpclient.OnFatalError += delegate(object sender, AxMSTSCLib.IMsTscAxEvents_OnFatalErrorEvent e)
                {
                    //MessageBox.Show("OnFatalError");
                    lock (_lockErrorsFile)
                    {
                        using (StreamWriter w = new StreamWriter(pathToErrors, true))
                        {
                            w.WriteLine(string.Format("{0}@{1};{2} - {3}", rdpData.IP, rdpData.Login, rdpData.Password, e.ToString()));
                        }
                    }
                };

                string currentDirectory = Directory.GetCurrentDirectory();
                string pathToIpLoginPasswordDB = currentDirectory + "\\" + "IpLoginPasswordDB.txt";
                string pathToCurrentIP = currentDirectory + "\\currentIP.txt";
                long currentLine;

                if (!File.Exists(pathToCurrentIP)) File.Create(pathToCurrentIP);

                while (true)
                {
                    if (_shouldStop) break;

                    List<RDPData> listRdpData = new List<RDPData>();

                    lock (_lockGenRDPFile)
                    {

                        using (StreamReader r = new StreamReader(pathToCurrentIP))
                        {
                            long.TryParse(r.ReadLine(), out currentLine);
                        }

                        using (StreamReader r = new StreamReader(pathToIpLoginPasswordDB))
                        {
                            string IP = string.Empty;
                            int needReedLines = 1;  
                            string line = string.Empty;

                            for (int i = 0; i < currentLine; i++)
                            {
                                line = r.ReadLine();
                                if (string.IsNullOrEmpty(line)) goto Exit;
                            }

                            for (int j = 0; j < needReedLines; j++)
                            {
                                line = r.ReadLine();

                                if (!string.IsNullOrEmpty(line))
                                {
                                    currentLine++;

                                    string[] arrLines = line.Split(new char[] { ';' });

                                    if (arrLines != null && arrLines.Length == 3)
                                    {
                                        rdpData = new RDPData();

                                        rdpData.IP = arrLines[0];
                                        rdpData.Login = arrLines[1];
                                        rdpData.Password = arrLines[2];

                                        listRdpData.Add(rdpData);
                                    }

                                }
                                else break;
                            }
                        }

                        using (StreamWriter w = new StreamWriter(pathToCurrentIP))
                        {
                            w.WriteLine(currentLine.ToString());
                        }
                    }

                    mre = new ManualResetEvent(false); 

                    if (listRdpData.Count == 0) goto Exit;

                    for (int i = 0; i < listRdpData.Count; i++)
                    {
                        lock (_lockProgressBar)
                        {
                            
                            SetProgressValue(Convert.ToInt32(((_countHandledRecords * 100) / countDbRecords)));
                        }

                        rdpData = listRdpData[i];

                        if (rdpData != null)
                        {
                            lock (_lockRDPClientControl)
                            {
                                 
                                rdpclient.UserName = rdpData.Login;
                                //IMsTscNonScriptable secured = (IMsTscNonScriptable)rdpclient.GetOcx();
                                //secured.ClearTextPassword =  rdpData.Password;
                                rdpclient.AdvancedSettings2.ClearTextPassword = rdpData.Password;
                                rdpclient.Server = rdpData.IP;
                                rdpclient.Connect();
                            }

                            System.Threading.Timer timer = new System.Threading.Timer(delegate(object source)
                            {
                                rdpclient.Disconnect();
                                timer = null;
                            });

                            timer.Change(TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(-1));

                            mre.Reset();

                            mre.WaitOne();

                            if (!bOnLoginComplete && bOnConnected)
                            {
                                lock (_lockErrorsFile)
                                {
                                    using (StreamWriter w = new StreamWriter(pathToErrors, true))
                                    {
                                        w.WriteLine(string.Format("{0}@{1};{2}", rdpData.IP, rdpData.Login, rdpData.Password));
                                    }
                                }
                            }

                            if (!bOnLoginComplete && !bOnConnected && bOnConnecting)
                            {
                                lock (_lockBadHostsFile)
                                {
                                    using (StreamWriter w = new StreamWriter(pathToBadHosts, true))
                                    {
                                        w.WriteLine(string.Format("{0}", rdpData.IP));
                                    }
                                }
                            }

                            bOnConnecting = false;
                            bOnConnected = false;
                            bOnLoginComplete = false;

                            _countHandledRecords++;
                        }
                    }

                    lock (_lockProgressBar)
                    {
                        
                        SetProgressValue(Convert.ToInt32(((_countHandledRecords * 100) / countDbRecords)));
                    }
                }

            Exit: ;
                SetCountThreads(string.Format("Threads:{0}", --_countThreads));


                if (_countThreads == 0)
                {
                    int wParam = 0;
                    long lParam = 0;

                    PostMessage((int)form1.Handle, form1.queryCancelOperation, wParam, lParam);
                    SetCountThreads(string.Format("Finish! Потоков:{0}", 0));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\\n" + ex.StackTrace);
            }
        }
        
    }

    class RDPData
    {
        public RDPData() { }

        public string IP;
        public string Login;
        public string Password;
    }

推荐答案

请查看您的锁定机制.尝试访问rdpData.Login并设置rdpClient.UserName时,请确保没有冲突线程.

另外,请确保rdpData.Login有一个值.
Please see your locking mechanisms. Be sure you don''t have clashing threads when attempting to access rdpData.Login and set rdpClient.UserName..

Also, be sure rdpData.Login has a value.


这篇关于在多线程中使用多个AxMsRdpClient7NotSafeForScripting的问题.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆