System.Threading.ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback)

Here are the examples of the csharp api System.Threading.ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1039 Examples 7

19 View Source File : WebhookServer.cs
License : MIT License
Project Creator : 4egod

private void ProcessRequest(string body)
        {
            var e = JsonConvert.DeserializeObject<Event>(body);

            foreach (var entry in e.Entries)
            {
                foreach (var item in entry.Items)
                {
                    if (item.Message != null && MessageReceived != null)
                    {
                        MessageEventArgs messageEventArgs = new MessageEventArgs()
                        {
                            Sender = item.Sender.Id,
                            Message = item.Message
                        };

                        ThreadPool.QueueUserWorkItem(state => MessageReceived.Invoke(messageEventArgs));
                    }

                    if (item.Postback != null && PostbackReceived != null)
                    {
                        PostbackEventArgs postbackEventArgs = new PostbackEventArgs()
                        {
                            Sender = item.Sender.Id,
                            Postback = item.Postback
                        };

                        ThreadPool.QueueUserWorkItem(state => PostbackReceived.Invoke(postbackEventArgs));
                    }
                }
            }
        }

19 View Source File : DeviceManager.cs
License : MIT License
Project Creator : aguang-xyz

private void FireDevicesChangedLater()
        {
            ThreadPool.QueueUserWorkItem(_ =>
            {
                DevicesChanged?.Invoke(this, EventArgs.Empty);
            });
        }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void StartR2L()
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {
                remoteToLocalRun = true;
                if (remoteQueue.Count > 0)
                {
                    while (remoteToLocalRun)
                    {
                        try
                        {
                            RunRemoteToLocal();
                        }
                        catch { }
                        Thread.Sleep(100);
                    }
                }                
                remoteToLocalRun = false;
            });
        }

19 View Source File : FrmBatch.cs
License : MIT License
Project Creator : 2881099

private async void command_export_Executed(object sender, EventArgs e)
        {

            Properties.Settings.Default.Save();
            if (listBoxAdv2.Items.Count == 0)
            {
                MessageBoxEx.Show("请选择表");
                return;
            }
            if (string.IsNullOrEmpty(textBoxX1.Text))
            {
                MessageBoxEx.Show("命名空间不能为空");
                return;
            }
            if (string.IsNullOrEmpty(textBoxX4.Text))
            {
                MessageBoxEx.Show("请选择导出路径");
                return;
            }
            if (listBoxAdv3.CheckedItems.Count == 0)
            {
                MessageBoxEx.Show("请选择生成模板");
                return;
            }
            var templates = listBoxAdv3.CheckedItems.Cast<ListBoxItem>().Select(a => a.Text).ToArray();     
            var taskBuild = new TaskBuild()
            {
                Fsql = G.GetFreeSql(_node.DataKey),
                DbName = _node.Text,
                FileName = textBoxX3.Text,
                GeneratePath = textBoxX4.Text,
                NamespaceName = textBoxX1.Text,
                RemoveStr = textBoxX2.Text,
                OptionsEnreplacedy01 = checkBoxX1.Checked,
                OptionsEnreplacedy02 = checkBoxX2.Checked,
                OptionsEnreplacedy03 = checkBoxX3.Checked,
                OptionsEnreplacedy04 = checkBoxX4.Checked,
                Templates = templates
            };
            var tables = listBoxAdv2.Items.Cast<string>().ToArray();
            var tableInfos = dbTableInfos.Where(a => tables.Contains(a.Name)).ToList();
            FrmLoading frmLoading=null;
            ThreadPool.QueueUserWorkItem(new WaitCallback(a =>
            {
                this.Invoke((Action)delegate ()
                {
                    frmLoading = new FrmLoading("正在生成中,请稍后.....");
                    frmLoading.ShowDialog();
                });
            }));
            await new CodeGenerate().Setup(taskBuild, tableInfos);
            this.Invoke((Action)delegate () { frmLoading?.Close(); });

        }

19 View Source File : SftpLinuxForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void newFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InputForm form = new InputForm("请输入文件夹名称", "", new InputForm.FormResult((name) => {
                if(!string.IsNullOrWhiteSpace(name)){

                    SendShell("mkdir -p " + getCurrDir() + Utils.getLinuxName(name));

                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        RefreshFiles();
                    });
                }
                else
                {
                    MessageBox.Show(this, "名称不能为空");
                }                
            }));
            form.ShowDialog(this);
        }

19 View Source File : TomcatMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void btn_restart_Click(object sender, EventArgs e)
        {
            monitorForm.RunShell(l_tomcat_path.Text + "bin/shutdown.sh", false, true);

            CheckItem();
            ThreadPool.QueueUserWorkItem((a) =>
            {
                Thread.Sleep(15);

                monitorForm.RunShell(l_tomcat_path.Text + "bin/startup.sh", false, true);

                CheckItem();
            });            
        }

19 View Source File : UdpSocket.cs
License : Apache License 2.0
Project Creator : advancer68

public void Connect(string host, int port)
        {
            mSvrEndPoint = new IPEndPoint(IPAddress.Parse(host), port);
            mUdpClient = new UdpClient(host, port);
            UnityEngine.Debug.LogFormat("snd buff size:{0},rcv buff size:{1}", mUdpClient.Client.SendBufferSize, mUdpClient.Client.ReceiveBufferSize);
            mUdpClient.Connect(mSvrEndPoint);
            state = State.Connect;
            //init_kcp((UInt32)new Random((int)DateTime.Now.Ticks).Next(1, Int32.MaxValue));
            init_kcp(0);
            if (rcvSync)
            {
                mUdpClient.BeginReceive(ReceiveCallback, this);
            }
            else
            {
                //ThreadPool.QueueUserWorkItem(new WaitCallback(process_rcv_queue));
            }
            ThreadPool.QueueUserWorkItem(new WaitCallback(process_kcpio_queue));
        }

19 View Source File : MonitorItemForm.cs
License : Apache License 2.0
Project Creator : 214175590

void Tomcat_TextChanged(object sender, EventArgs e)
        {
            string path = stb_tomcat_path.Text;
            if (!string.IsNullOrWhiteSpace(path))
            {
                if (string.IsNullOrWhiteSpace(tomcat_name))
                {
                    try
                    {
                        stb_tomcat_name.Text = path.Substring(path.LastIndexOf("/") + 1);
                    }
                    catch { }
                }

                if (string.IsNullOrWhiteSpace(stb_tomcat_port.Text))
                {
                    try
                    {
                        if (get_tomcat_port_run)
                        {
                            return;
                        }
                        get_tomcat_port_run = true;
                        if (!path.EndsWith("/"))
                        {
                            path += "/";
                        }
                        string serverxml = path + "conf/server.xml";
                        string targetxml = MainForm.TEMP_DIR + string.Format("server-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
                        targetxml = targetxml.Replace("\\", "/");
                        parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                        ThreadPool.QueueUserWorkItem((a) => {
                            Thread.Sleep(500);

                            List<Hashtable> list = YSTools.YSXml.readXml(targetxml, "Server");
                            if(list != null && list.Count > 0){
                                List<Hashtable> serviceList = null;
                                string port = null;
                                foreach(Hashtable one in list){
                                    if (one["NodeName"].ToString() == "Service")
                                    {
                                        serviceList = (List<Hashtable>) one["ChildList"];
                                        foreach (Hashtable two in serviceList)
                                        {
                                            if (two["NodeName"].ToString() == "Connector")
                                            {
                                                port = two["port"].ToString();

                                                break;
                                            }
                                        }
                                        if(port != null){
                                            break;
                                        }
                                    }
                                }

                                stb_tomcat_port.BeginInvoke((MethodInvoker)delegate()
                                {
                                   stb_tomcat_port.Text = port == null ? "8080" : port;
                                });
                            }
                            get_tomcat_port_run = false;

                            File.Delete(targetxml);
                        });
                    }
                    catch { }
                }
            }
        }

19 View Source File : MediaManager.cs
License : MIT License
Project Creator : aguang-xyz

public async Task<IEnumerable<PlayList>> GetPlayListAsync(Episode episode)
        {
            try
            {
                var url = $"http://light-player/media/{episode.ProviderId}/play-lists.json?externalId={episode.ExternalId}";
                var cacheFileName = PathUtils.GetCacheFileName("json", url);

                // Try to load play lists from cache first.
                var cachedPlayLists = await ReadJsonAsync<PlayList[]>(cacheFileName);
                if (cachedPlayLists != null)
                {
                    // If the cache is older than 10 minutes ago, we will trigger an refresh.
                    if (File.GetLastWriteTime(cacheFileName) < DateTime.Now.AddMinutes(10))
                    {
                        ThreadPool.QueueUserWorkItem(async _ =>
                        {
                            await WriteJsonAsync(cacheFileName, (await GetProvider(episode.ProviderId).GetPlayListsAsync(episode)).ToArray());
                        });
                    }
                    
                    return cachedPlayLists;
                }

                var playLists = (await GetProvider(episode.ProviderId).GetPlayListsAsync(episode)).ToArray();

                await WriteJsonAsync(cacheFileName, playLists);

                return playLists;
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "Failed to get play lists {ProviderId} {ExternalId}", episode.ProviderId, episode.ExternalId);
                return Array.Empty<PlayList>();
            }
        }

19 View Source File : ControlUtil.cs
License : Apache License 2.0
Project Creator : 214175590

public static void delayClearText(DelayDelegate dele, int millis)
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {
                Thread.Sleep(millis);
                dele();
            });
        }

19 View Source File : SftpWinForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void listView1_MouseUp(object sender, MouseEventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                int index = listView1.SelectedIndices[0];
                string name = listView1.SelectedItems[0].Text;
                if (name == ".." && index == 0)
                {
                    listView1.ContextMenuStrip = null;
                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(100);
                        this.BeginInvoke((MethodInvoker)delegate()
                        {
                            listView1.ContextMenuStrip = contextMenuStrip1;
                        });
                    });
                }
            }
        }

19 View Source File : SftpLinuxForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (COPY_QUEUE.Count > 0)
            {
                string[] items = null;
                string path1, path2;
                for (int i = 0, k = COPY_QUEUE.Count; i < k; i++ )
                {
                    items = COPY_QUEUE.Dequeue();
                    path1 = items[0] + items[1];
                    path2 = getCurrDir();
                    SendShell(string.Format("cp {0} {1}", path1, path2));
                }
                pasteToolStripMenuItem.Enabled = false;

                ThreadPool.QueueUserWorkItem((a) =>
                {
                    Thread.Sleep(500);
                    RefreshFiles();
                });
            }
        }

19 View Source File : SftpWinForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void newFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InputForm form = new InputForm("请输入文件夹名称", "", new InputForm.FormResult((name) =>
            {
                if (!string.IsNullOrWhiteSpace(name))
                {
                    DirectoryInfo dire = new DirectoryInfo(getCurrDir() + name);
                    if(!dire.Exists){
                        dire.Create();
                    }
                    else
                    {
                        MessageBox.Show(this, "目录已存在");
                    }

                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        RefreshFiles();
                    });
                }
                else
                {
                    MessageBox.Show(this, "名称不能为空");
                }
            }));
            form.ShowDialog(this);
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 2881099

async void LoadDataInfo(Node node)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(a =>
            {
                frmLoading = new FrmLoading();
                frmLoading.ShowDialog();
            }));
            var res = await Task.Run(() =>
             {

                 if (node.Level == 1)
                 {
                     if (node.Nodes.Count >= 1) return 0;
                     node.Nodes.Clear();
                     var list = G.GetDatabases(node.DataKey, node.TagString);
                     var nodes = list.Select(a => new Node(a)
                     {
                         Image = Properties.Resources._base,
                         DataKey = node.DataKey,
                         ContextMenu = buttonItem22
                     }).ToArray();
                     node.Nodes.AddRange(nodes);
                 }
                 else if (node.Level == 2)
                 {
                     node.Nodes.Clear();
                     Task.Delay(1000);
                     var list = G.GetTablesByDatabase(node.DataKey, node.Text);
                     var nodes = list.Select(a => new Node(a.Name)
                     {
                         Image = Properties.Resources.application,
                        // CheckBoxVisible = true,
                        // CheckBoxStyle = DevComponents.DotNetBar.eCheckBoxStyle.CheckBox,
                        // CheckState = CheckState.Unchecked,
                         Tag = a,
                         DataKey = node.DataKey,
                         ContextMenu = buttonItem23
                     }).ToArray();
                     node.Nodes.AddRange(nodes);
                 }
                 return 0;
             });
            node.Expanded = true;
            this.Invoke((Action)delegate () { Thread.CurrentThread.Join(500); frmLoading.Close(); });
        }

19 View Source File : IceMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void runTaskShell(CmdShell cmds, TaskShell task)
        {
            ThreadPool.QueueUserWorkItem((a) => {

                string srvdir = itemConfig.ice.IceSrvDir;
                if (null != srvdir)
                {
                    if (!srvdir.EndsWith("/"))
                    {
                        srvdir += "/";
                    }
                }

                string shell = task.Shell;
                if (shell.Contains("{icesrv_dir}"))
                {
                    shell = shell.Replace("{icesrv_dir}", srvdir);
                }

                if (shell.Contains("{server_name}"))
                {
                    shell = shell.Replace("{server_name}", l_server_name.Text);
                }

                if (shell.Contains("{adminsh}"))
                {
                    shell = shell.Replace("{adminsh}", srvdir + "bin/admin.sh");
                }
                shell = shell.Replace("//", "/");

                monitorForm.RunShell(shell, false);
            });
        }

19 View Source File : Job.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static void StartNew(WaitCallback waitCallback,DoneSyncCallback doneSyncCallback,Token token=null)
        {
            ThreadPool.QueueUserWorkItem(state => {

                if (null != waitCallback)
                {
                    JobState jobState = new JobState();
                    jobState.Token = token ?? new Token();
                    jobState.State = state;
                    waitCallback.Invoke(jobState);
                    EnSyncStateQueue(jobState,doneSyncCallback);
                }

            });
        }

19 View Source File : TomcatMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void LoadProjectList()
        {
            ThreadPool.QueueUserWorkItem((a) => {
                List<JObject> itemList = new List<JObject>();
                // 1、获取webapps下的项目
                ArrayList files = (ArrayList)monitorForm.RunSftpShell(string.Format("ls {0}webapps/", l_tomcat_path.Text), false, false);
                if (files != null)
                {
                    string dirname = "";
                    JObject json = null;
                    Object obj = null;
                    for (int ii = 0; ii < files.Count; ii++)
                    {
                        obj = files[ii];
                        if (obj is ChannelSftp.LsEntry)
                        {
                            dirname = ((ChannelSftp.LsEntry)obj).getFilename();
                            if (dirname.IndexOf(".") == -1 && dirname.IndexOf(":") == -1)
                            {
                                json = new JObject();
                                json.Add("name", dirname);
                                json.Add("url", l_visit_url.Text + (dirname == "ROOT" ? "" : "/" + dirname));
                                json.Add("path", l_tomcat_path.Text + "webapps/" + dirname);
                                itemList.Add(json);
                            }
                        }
                    }
                }
                // 2、获取server.xml中的映射配置
                List<JObject> itemList2 = loadTomcatServerProject();
                foreach (JObject p in itemList2)
                {
                    itemList.Add(p);
                }
                // 渲染列表
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    projects.Items.Clear();
                    ListViewItem item = null;
                    ListViewItem.ListViewSubItem subItem = null;
                    foreach (JObject pro in itemList)
                    {
                        item = new ListViewItem();
                        item.Tag = pro;
                        item.Name = pro["name"].ToString();
                        item.Text = pro["url"].ToString();

                        subItem = new ListViewItem.ListViewSubItem();
                        subItem.Text = pro["path"].ToString();
                        item.SubItems.Add(subItem);
                    
                        projects.Items.Add(item);
                    }
                });
            });
        }

19 View Source File : TrackGenerator.cs
License : Apache License 2.0
Project Creator : Aggrathon

IEnumerator Coroutine()
	{
		Utils.ClearMemory();
		if (terrainData == null || terrain == null)
		{
			CreateTerrain();
			yield return null;
		}

		heights = terrainData.GetHeights(0, 0, terrainData.heightmapWidth, terrainData.heightmapHeight);
		alphas = terrainData.GetAlphamaps(0, 0, terrainData.alphamapWidth, terrainData.alphamapHeight);
		Vector3 position = terrain.transform.position;
		float waterRelativeHeight = water.position.y / size.y;

		//Generate heights
		terrainGenerator.SetupConfig();
		bool terrainHeights1 = true;
		ThreadPool.QueueUserWorkItem((o) => {
			terrainGenerator.GenerateHeights(heights, 0, 4);
			terrainHeights1 = false;
		});
		bool terrainHeights2 = true;
		ThreadPool.QueueUserWorkItem((o) => {
			terrainGenerator.GenerateHeights(heights, 1, 4);
			terrainHeights2 = false;
		});
		bool terrainHeights3 = true;
		ThreadPool.QueueUserWorkItem((o) => {
			terrainGenerator.GenerateHeights(heights, 2, 4);
			terrainHeights3 = false;
		});
		bool terrainHeights4 = true;
		ThreadPool.QueueUserWorkItem((o) => {
			terrainGenerator.GenerateHeights(heights, 3, 4);
			terrainHeights4 = false;
		});

		while (terrainHeights1 || terrainHeights2 || terrainHeights3 || terrainHeights4)
			yield return null;
		//create roads
		bool road = true;
		ThreadPool.QueueUserWorkItem((o) => {
			roadGenerator.Generate(heights, size, position, waterRelativeHeight);
			road = false;
		});

		//paint textures
		bool terrainTextures = true;
		ThreadPool.QueueUserWorkItem((o) => {
			terrainGenerator.PrepareTextures(heights, waterRelativeHeight);
			terrainTextures = false;
		});
		while (terrainTextures)
			yield return null;
		bool terrainTextures1 = true;
		ThreadPool.QueueUserWorkItem((o) => {
			terrainGenerator.GenerateTextures(heights, alphas, 0, 4);
			terrainTextures1 = false;
		});
		bool terrainTextures2 = true;
		ThreadPool.QueueUserWorkItem((o) => {
			terrainGenerator.GenerateTextures(heights, alphas, 1, 4);
			terrainTextures2 = false;
		});
		bool terrainTextures3 = true;
		ThreadPool.QueueUserWorkItem((o) => {
			terrainGenerator.GenerateTextures(heights, alphas, 2, 4);
			terrainTextures3 = false;
		});
		bool terrainTextures4 = true;
		ThreadPool.QueueUserWorkItem((o) => {
			terrainGenerator.GenerateTextures(heights, alphas, 3, 4);
			terrainTextures4 = false;
		});

		//level roads
		while (road)
			yield return null;
		bool roadHeights = true;
		ThreadPool.QueueUserWorkItem((o) => {
			roadGenerator.DrawRoadHeights(heights, size, position, alphas.GetLength(0));
			roadHeights = false;
		});

		//paint roads
		while (road || terrainTextures1 || terrainTextures2 || terrainTextures3 || terrainTextures4)
			yield return null;
		bool roadTextures = true;
		ThreadPool.QueueUserWorkItem((o) => {
			roadGenerator.DrawRoadTextures(alphas, size, position);
			roadTextures = false;
		});

		while (roadTextures || roadHeights)
			yield return null;
		terrainData.SetHeights(0, 0, heights);
		terrainData.SetAlphamaps(0, 0, alphas);
		terrain.Flush();

		yield return null;
		reflection.RenderProbe();
		Utils.ClearMemory();
		if (onGenerated != null)
			onGenerated();
	}

19 View Source File : NginxMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void StartCheckItems()
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    NginxMonitorUrl pro = null;
                    foreach (ListViewItem item in projects.Items)
                    {
                        pro = (NginxMonitorUrl) item.Tag;
                        if(pro.check){
                            CheckItem(pro.url, item);
                        }
                    }
                });
            });
        }

19 View Source File : MediaManager.cs
License : MIT License
Project Creator : aguang-xyz

public async Task<StreamInfo> GetStreamInfoAsync(Video video)
        {
            try
            {
                var url = $"http://light-player/media/{video.ProviderId}/live-stream.json?externalId={video.ExternalId}";
                var cacheFileName = PathUtils.GetCacheFileName("json", url);

                var cachedStream = await ReadJsonAsync<StreamInfo>(cacheFileName);

                if (cachedStream != null)
                {
                    if (File.GetLastWriteTime(cacheFileName) < DateTime.Now.AddMinutes(10))
                    {
                        ThreadPool.QueueUserWorkItem(async _ =>
                        {
                            await WriteJsonAsync(cacheFileName, await GetProvider(video.ProviderId).GetStreamInfoAsync(video));
                        });
                    }
                    
                    return cachedStream;
                }

                var streamUrl = await GetProvider(video.ProviderId).GetStreamInfoAsync(video);

                await WriteJsonAsync(cacheFileName, streamUrl);
                
                return streamUrl;
            }
            catch (Exception)
            {
                _logger.LogWarning("Failed to get live stream URL {ProviderId} {ExternalId}", video.ProviderId, video.ExternalId);
                return null;
            }
        }

19 View Source File : MainForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.Text = appName + " v" + appVersion;

                string str = YSTools.YSFile.readFileToString(MyDoreplacedents + "\\." + appName);
                if(!string.IsNullOrWhiteSpace(str)){
                    MessageBox.Show(str);
                    Application.Exit();
                }
            }
            catch { }

            tsp_font_fimily.SelectedIndex = 3;
            tsp_font_size.SelectedIndex = 0;

            init();
            ThreadPool.QueueUserWorkItem((a) => {
                if (AppConfig.Instance.MConfig.OnstartShowSessMgt)
                {
                    this.BeginInvoke((MethodInvoker)delegate()
                    {
                        SessionManageForm form = new SessionManageForm();
                        form.ShowDialog(this);

                        RenderSessionList();
                    });                    
                }
            });
        }

19 View Source File : SftpLinuxForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void Connect()
        {
            shell = new SshShell(user.Host, user.UserName, YSEncrypt.DecryptB(user.Preplacedword, KeysUtil.PreplacedKey));

            shell.Connect(user.Port);

            m_Channel = shell.getChannel();
            session = shell.getSession();

            sftpChannel = (ChannelSftp)session.openChannel("sftp");
            sftpChannel.connect();

            ThreadPool.QueueUserWorkItem((a) =>
            {
                string line = null;
                while (RUN_CUT && shell.ShellOpened)
                {
                    success = true;
                    logger.Debug("Successed...");
                    sftpForm.HideTool();

                    System.Threading.Thread.Sleep(100);
                    while ((line = m_Channel.GetMessage()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }

                logger.Debug("Disconnecting...");
                Disconnection();
                logger.Debug("OK");
                
            });

            dir = sftpChannel.getHome();

            text_adress.Text = dir;

            LoadDirFilesToListView(dir);

            SetContentMenuItem(true);
        }

19 View Source File : MonitorItemForm.cs
License : Apache License 2.0
Project Creator : 214175590

void SrvPath_TextChanged(object sender, EventArgs e)
        {
            string path = stb_ice_srvpath.Text;
            if (!string.IsNullOrWhiteSpace(path))
            {
                string appname = stb_ice_appname.Text;

                if (!string.IsNullOrWhiteSpace(appname) && string.IsNullOrWhiteSpace(stb_ice_ports.Text))
                {
                    try
                    {
                        if (get_ice_port_run)
                        {
                            return;
                        }
                        get_ice_port_run = true;
                        if (!path.EndsWith("/"))
                        {
                            path += "/";
                        }
                        string serverxml = string.Format("{0}config/{1}.xml", path, appname);
                        string targetxml = MainForm.TEMP_DIR + string.Format("srv-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
                        targetxml = targetxml.Replace("\\", "/");
                        parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                        ThreadPool.QueueUserWorkItem((a) =>
                        {
                            Thread.Sleep(500);

                            List<Hashtable> list = YSTools.YSXml.readXml(targetxml, "icegrid");
                            if (list != null && list.Count > 0)
                            {
                                List<Hashtable> appList = null, nodeList = null;
                                List<Hashtable> serverList = null;
                                string ports = "", nodeName = "", serverName = "";
                                foreach (Hashtable one in list)
                                {
                                    if (one["NodeName"].ToString() == "application")
                                    {
                                        appList = (List<Hashtable>)one["ChildList"];
                                        foreach (Hashtable two in appList)
                                        {
                                            if (two["NodeName"].ToString() == "node")
                                            {
                                                nodeName = two["name"].ToString();
                                                nodeList = (List<Hashtable>)two["ChildList"];
                                                foreach (Hashtable four in nodeList)
                                                {
                                                    if (four["NodeName"].ToString() == "server-instance")
                                                    {
                                                        ports += "," + four["serverport"].ToString();
                                                    }
                                                }

                                            }

                                            if (two["NodeName"].ToString() == "server-template")
                                            {
                                                serverList = (List<Hashtable>)two["ChildList"];
                                                foreach (Hashtable four in serverList)
                                                {
                                                    if (four["NodeName"].ToString() == "icebox")
                                                    {
                                                        serverName = four["id"].ToString();
                                                        serverName = serverName.Substring(0, serverName.IndexOf("$")) + "1";
                                                        break;
                                                    }
                                                }
                                            }

                                            if (ports != "")
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                                                                
                                stb_ice_ports.BeginInvoke((MethodInvoker)delegate()
                                {
                                    stb_ice_servername.Text = serverName;
                                    stb_ice_ports.Text = ports == "" ? "8082" : ports.Substring(1);
                                });
                            }
                            get_ice_port_run = false;

                            File.Delete(targetxml);
                        });
                    }
                    catch { }
                }
            }
        }

19 View Source File : SftpLinuxForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int count = listView2.SelectedItems.Count;
            if (count > 0)
            {
                DialogResult dr = MessageBox.Show(this, "您确定要删除选择的文件或文件夹吗?", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                if(dr == System.Windows.Forms.DialogResult.OK){
                    string dirs = getCurrDir();
                    foreach (ListViewItem item in listView2.SelectedItems)
                    {
                        SendShell("rm -rf " + dirs + Utils.getLinuxName(item.Text));
                    }

                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        RefreshFiles();
                    });
                }                
            }
        }

19 View Source File : MonitorItemForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void button1_Click(object sender, EventArgs e)
        {
            int index = tabControl1.SelectedIndex;
            bool isnew = false;
            if (monitorConfig == null)
            {
                isnew = true;                
            }
            else
            {
                index = tabIndex;
            }
            if (index == 0)
            { // springboot
                SpringBootMonitorItem item = new SpringBootMonitorItem();                
                item.AppName = stb_app_name.Text;
                item.BuildFileName = stb_build_file.Text;
                item.CrlFileName = stb_ctl_file.Text;
                item.ShFileDir = stb_sh_dir.Text;
                if (item.ShFileDir.EndsWith("/"))
                {
                    item.ShFileDir = item.ShFileDir.Substring(0, item.ShFileDir.Length);
                }
                item.ProjectSourceDir = stb_project_source_dir.Text;
                if (item.ProjectSourceDir.EndsWith("/"))
                {
                    item.ProjectSourceDir = item.ProjectSourceDir.Substring(0, item.ProjectSourceDir.Length);
                }
                item.HomeUrl = stb_home_url.Text;
                item.RunStatus = RunState.NoCheck;
                if (string.IsNullOrWhiteSpace(item.HomeUrl))
                {
                    item.HomeUrl = "http://" + config.Host + ":8080/";
                }
                if (string.IsNullOrWhiteSpace(item.AppName) || hasNonChar(item.AppName))
                {
                    MessageBox.Show(this, "请填写应用名称,且不能包含'\",:;|");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.ShFileDir))
                {
                    MessageBox.Show(this, "请填写应用脚本目录");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.BuildFileName))
                {
                    MessageBox.Show(this, "请填写应用编译脚本文件名称");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.CrlFileName))
                {
                    MessageBox.Show(this, "请填写应用控制脚本文件名称");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.ProjectSourceDir))
                {
                    MessageBox.Show(this, "请填写应用代码存放目录");
                    return;
                }

                item.NeedAdd = cb_need_add.Checked;
                if (item.NeedAdd)
                {
                    item.ProjectSvnUrl = stb_project_svn.Text;
                    if (string.IsNullOrWhiteSpace(item.ProjectSvnUrl))
                    {
                        MessageBox.Show(this, "请填写应用SVN地址");
                        return;
                    }
                }
                if (isnew)
                {
                    item.Uuid = Guid.NewGuid().ToString("N");
                    monitorConfig = new MonitorItemConfig();
                }
                else
                {
                    item.Uuid = monitorConfig.spring.Uuid;
                }
                monitorConfig.spring = item;
            }
            else if (index == 1)
            { // tomcat
                TomcatMonitorItem item = new TomcatMonitorItem();                
                item.TomcatName = stb_tomcat_name.Text;
                item.TomcatDir = stb_tomcat_path.Text;
                item.TomcatPort = stb_tomcat_port.Text;
                item.RunStatus = RunState.NoCheck;
                if (string.IsNullOrWhiteSpace(item.TomcatName) || hasNonChar(item.TomcatName))
                {
                    MessageBox.Show(this, "请填写Tomcat名称,且不能包含'\",:;|");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.TomcatDir))
                {
                    MessageBox.Show(this, "请填写Tomcat根目录");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.TomcatPort))
                {
                    item.TomcatPort = "8080";
                }
                if (isnew)
                {
                    item.Uuid = Guid.NewGuid().ToString("N");
                    monitorConfig = new MonitorItemConfig();
                }
                else
                {
                    item.Uuid = monitorConfig.tomcat.Uuid;
                }
                monitorConfig.tomcat = item;
            }
            else if (index == 2)
            { // nginx
                NginxMonitorItem item = new NginxMonitorItem();                
                item.NginxName = stb_nginx_name.Text;
                item.NginxPath = stb_nginx_path.Text;
                item.NginxConfig = stb_nginx_conf.Text;
                item.RunStatus = RunState.NoCheck;
                if (string.IsNullOrWhiteSpace(item.NginxName) || hasNonChar(item.NginxName))
                {
                    MessageBox.Show(this, "请填写Nginx名称,且不能包含'\",:;|");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.NginxPath))
                {
                    MessageBox.Show(this, "请填写Nginx执行文件完整路径");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.NginxConfig))
                {
                    MessageBox.Show(this, "请填写Nginx配置文件完整路径");
                    return;
                }
                if (isnew)
                {
                    monitorConfig = new MonitorItemConfig();
                    item.Uuid = Guid.NewGuid().ToString("N");
                }
                else
                {
                    item.Uuid = monitorConfig.nginx.Uuid;
                }
                monitorConfig.nginx = item;
            }
            else if (index == 3)
            { // ice
                IceMonitorItem item = new IceMonitorItem();
                item.AppName = stb_ice_appname.Text;
                item.IceSrvDir = stb_ice_srvpath.Text;
                item.NodePorts = stb_ice_ports.Text;
                item.ServerName = stb_ice_servername.Text;
                item.RunStatus = RunState.NoCheck;
                if (string.IsNullOrWhiteSpace(item.AppName) || hasNonChar(item.AppName))
                {
                    MessageBox.Show(this, "请填写项目名称,且不能包含'\",:;|");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.IceSrvDir))
                {
                    MessageBox.Show(this, "请填写项目Ice目录完整路径");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.ServerName))
                {
                    MessageBox.Show(this, "请填写Ice服务名称");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.NodePorts))
                {
                    MessageBox.Show(this, "请填写项目使用的端口号,多个以逗号(,)分隔");
                    return;
                }
                if (isnew)
                {
                    monitorConfig = new MonitorItemConfig();
                    item.Uuid = Guid.NewGuid().ToString("N");
                }
                else
                {
                    item.Uuid = monitorConfig.ice.Uuid;
                }
                monitorConfig.ice = item;
            }


            if (isnew)
            {
                config.MonitorConfigList.Add(monitorConfig);
            }

            AppConfig.Instance.SaveConfig(2);

            if (null != parentForm && monitorConfig.spring != null)
            {
                // TODO 执行checkout
                if (monitorConfig.spring.NeedAdd)
                {
                    string home = parentForm.getSftp().getHome();
                    string buildStr = YSTools.YSFile.readFileToString(MainForm.CONF_DIR + "__build.sh");
                    string ctlStr = YSTools.YSFile.readFileToString(MainForm.CONF_DIR + "__ctl.sh");
                    if (monitorConfig.spring.ProjectSourceDir.StartsWith(home))
                    {
                        string path = monitorConfig.spring.ProjectSourceDir.Substring(home.Length);
                        if (path.StartsWith("/"))
                        {
                            path = path.Substring(1);
                        }
                        buildStr = buildStr.Replace("_sourcePath_", "~/" + path);
                        ctlStr = ctlStr.Replace("_sourcePath_", "~/" + path);
                    }
                    else
                    {
                        buildStr = buildStr.Replace("_sourcePath_", monitorConfig.spring.ProjectSourceDir);
                        ctlStr = ctlStr.Replace("_sourcePath_", monitorConfig.spring.ProjectSourceDir);
                    }
                    buildStr = buildStr.Replace("_projectName_", monitorConfig.spring.AppName);
                    ctlStr = ctlStr.Replace("_projectName_", monitorConfig.spring.AppName);
                    ctlStr = ctlStr.Replace("_disconfigUrl_", stb_disconfig_url.Text);                    

                    string localBuild = MainForm.CONF_DIR + monitorConfig.spring.BuildFileName;
                    string localCtl = MainForm.CONF_DIR + monitorConfig.spring.CrlFileName;
                    string remoteBuild = monitorConfig.spring.ShFileDir + "/" + monitorConfig.spring.BuildFileName;
                    string remoteCtl = monitorConfig.spring.ShFileDir + "/" + monitorConfig.spring.CrlFileName;

                    YSTools.YSFile.writeFileByString(localBuild, buildStr);
                    YSTools.YSFile.writeFileByString(localCtl, ctlStr);

                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        parentForm.BeginInvoke((MethodInvoker)delegate()
                        {
                            parentForm.getSftp().put(localBuild, remoteBuild, ChannelSftp.OVERWRITE);
                            parentForm.getSftp().put(localCtl, remoteCtl, ChannelSftp.OVERWRITE);

                            parentForm.RunShell("cd " + monitorConfig.spring.ProjectSourceDir, true);
                            parentForm.RunShell("svn checkout " + monitorConfig.spring.ProjectSvnUrl, true);

                            File.Delete(localBuild);
                            File.Delete(localCtl);
                        });
                    });
                }                
            }

            this.Close();
        }

19 View Source File : SftpWinForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int count = listView1.SelectedItems.Count;
            if (count == 1)
            {
                ListViewItem item = listView1.SelectedItems[0];
                Object tag = item.Tag;
                string path = getCurrDir() + item.Text;
                if (tag is FileInfo)
                {
                    FileInfo file = new FileInfo(path);
                    if (file.Exists)
                    {
                        file.Delete();
                    }
                }
                else if (tag is DirectoryInfo)
                {
                    DirectoryInfo dire = new DirectoryInfo(path);
                    if (dire.Exists)
                    {
                        dire.Delete(true);
                    }
                }

                ThreadPool.QueueUserWorkItem((a) =>
                {
                    Thread.Sleep(500);
                    RefreshFiles();
                });
            } 
        }

19 View Source File : SftpWinForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (COPY_QUEUE.Count > 0)
            {
                string[] items = null;
                string path1, path2;
                string currDir = getCurrDir();
                for (int i = 0, k = COPY_QUEUE.Count; i < k; i++)
                {
                    items = COPY_QUEUE.Dequeue();
                    path1 = items[0] + items[1];
                    path2 = currDir + items[1];
                    if (Utils.IsDir(path1))
                    {
                        Utils.CopyDir(path1, path2);
                    }
                    else
                    {
                        new FileInfo(path1).CopyTo(path2);
                    }
                }
                pasteToolStripMenuItem.Enabled = false;

                ThreadPool.QueueUserWorkItem((a) =>
                {
                    Thread.Sleep(500);
                    // 刷新
                    LoadDirFilesToListView(dir);
                });
            }
        }

19 View Source File : SftpLinuxForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void listView2_MouseUp(object sender, MouseEventArgs e)
        {
            if (listView2.SelectedItems.Count > 0)
            {
                int index = listView2.SelectedIndices[0];
                string name = listView2.SelectedItems[0].Text;
                if (name == ".." && index == 0)
                {
                    listView2.ContextMenuStrip = null;
                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(100);
                        this.BeginInvoke((MethodInvoker)delegate()
                        {
                            listView2.ContextMenuStrip = contextMenuStrip1;
                        });
                    });
                }
            }
        }

19 View Source File : SftpLinuxForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void renameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int count = listView2.SelectedItems.Count;
            if (count > 0)
            {
                ListViewItem row = listView2.SelectedItems[0];
                if (row != null)
                {
                    string oldName = row.Text;
                    ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry)row.Tag;
                    string msg = "请输入文件夹的新名称";
                    if(!entry.getAttrs().isDir()){
                        msg = "请输入文件的新名称";
                    }
                    InputForm form = new InputForm(msg, oldName, new InputForm.FormResult((newName) =>
                    {
                        if (oldName != newName)
                        {
                            string dirs = getCurrDir();
                            string path1 = dirs + Utils.getLinuxName(oldName);
                            string path2 = dirs + Utils.getLinuxName(newName);
                            SendShell(string.Format("mv {0} {1}", path1, path2));

                            ThreadPool.QueueUserWorkItem((a) =>
                            {
                                Thread.Sleep(500);
                                RefreshFiles();
                            });
                        }
                    }));
                    form.ShowDialog(this);
                }
            }            
        }

19 View Source File : ConditionTaskForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void InitCondition(int index, RenderFinishDelegate dele)
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    if (index == 1)
                    {
                        scb_condition1.Items.Clear();
                    }
                    else if (index == 2)
                    {
                        scb_condition2.Items.Clear();
                    }
                    else if (index == 3)
                    {
                        scb_condition3.Items.Clear();
                    }
                    ConditionItem condi = null;
                    foreach (MonitorItemConfig item in config.MonitorConfigList)
                    {
                        condi = new ConditionItem();
                        if (item.spring != null)
                        {
                            condi.Index = item.spring.Index;
                            condi.Item = item.spring;
                        }
                        else if (item.tomcat != null)
                        {
                            condi.Index = item.tomcat.Index;
                            condi.Item = item.tomcat;
                        }
                        else if (item.nginx != null)
                        {
                            condi.Index = item.nginx.Index;
                            condi.Item = item.nginx;
                        }
                        else if (item.ice != null)
                        {
                            condi.Index = item.ice.Index;
                            condi.Item = item.ice;
                        }

                        if (index == 1)
                        {
                            scb_condition1.Items.Add(condi);
                        }
                        else if (index == 2)
                        {
                            if (scb_condition1.SelectedItem == null 
                                || scb_condition1.SelectedItem.ToString() != condi.ToString())
                            {
                                scb_condition2.Items.Add(condi);
                            }                            
                        }
                        else if (index == 3)
                        {
                            if (scb_condition1.SelectedItem == null
                                || scb_condition1.SelectedItem.ToString() != condi.ToString())
                            {
                                if (scb_condition2.SelectedItem == null
                                || scb_condition2.SelectedItem.ToString() != condi.ToString())
                                {
                                    scb_condition3.Items.Add(condi);
                                }
                            }                            
                        }
                    }                    
                    if (null != dele)
                    {
                        dele(index);
                    }                    
                });
                System.Threading.Thread.Sleep(300);
            });
        }

19 View Source File : FrmBatch.cs
License : MIT License
Project Creator : 2881099

private void FrmBatch_Load(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(x => {
                frmLoading = new FrmLoading();
                frmLoading.ShowDialog();
            });
            labelX3.Text = _node.Parent.Text;
            labelX4.Text = _node.Text;
            LoadTableList();
            loadTemplates();
            Properties.Settings.Default.Reload();
            this.Invoke((Action)delegate { frmLoading.Close(); });
        }

19 View Source File : Form1.cs
License : Apache License 2.0
Project Creator : 214175590

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string host = tb_host.Text;
                string acc = tb_acc.Text;
                string pwd = tb_pwd.Text;

                shell = new SshShell(host, acc, pwd);

                //shell.RedirectToConsole();

                shell.Connect(22);

                m_Channel = shell.getChannel();
                
                string line = null;
                ThreadPool.QueueUserWorkItem((a) =>
                {
                    while (shell.ShellOpened)
                    {
                        System.Threading.Thread.Sleep(100);

                        while ((line = m_Channel.GetMessage()) != null)
                        {
                            ShowLogger(line);
                        }
                    }

                    Console.Write("Disconnecting...");
                    shell.Close();
                    Console.WriteLine("OK");
                });               

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            
        }

19 View Source File : WebhookServer.cs
License : MIT License
Project Creator : 4egod

private async Task Post(HttpRequest request, HttpResponse response, RouteData route)
        {
            var eventId = new EventId(_eventId++);

            try
            {
                byte[] buf = new byte[request.ContentLength.Value];
                await request.Body.ReadAsync(buf, 0, buf.Length);

                string body = Encoding.UTF8.GetString(buf);
                Logger.LogDebug(eventId, Resources.WebhookPost + body);
#if !DEBUG
                const string signatureHeader = "X-Hub-Signature";
                
                if (!request.Headers.Keys.Contains(signatureHeader))
                {
                    Logger.LogWarning(Resources.InvalidSignature);

                    if (PostFailed != null)
                    {
                        ThreadPool.QueueUserWorkItem(state => PostFailed.Invoke(new PostEventArgs()
                        {
                            Headers = request.Headers,
                            Body = body
                        }));
                    }

                    return;
                }

                var signature = request.Headers[signatureHeader][0];

                if (!VerifySignature(signature, buf))
                {
                    Logger.LogWarning(Resources.InvalidSignature);

                    if (PostFailed != null)
                    {
                        ThreadPool.QueueUserWorkItem(state => PostFailed.Invoke(new PostEventArgs()
                        {
                            Headers = request.Headers,
                            Body = body
                        }));
                    }

                    return;
                }
#endif          
                if (PostReceived != null)
                {
                    ThreadPool.QueueUserWorkItem(state => PostReceived.Invoke(new PostEventArgs()
                    {
                        Headers = request.Headers,
                        Body = body
                    }));
                }

                ProcessRequest(body);
            }
            catch (Exception e)
            {
                Logger.LogError(eventId, e, e.Message);
            }
        }

19 View Source File : MonitorItemForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void stb_home_url_Enter(object sender, EventArgs e)
        {
            string sdir = stb_project_source_dir.Text;
            string appname = stb_app_name.Text;
            string url = stb_home_url.Text;
            if(!string.IsNullOrWhiteSpace(sdir) && !string.IsNullOrWhiteSpace(appname) && url.EndsWith("[port]")){
                try
                {
                    if (get_spboot_port_run)
                    {
                        return;
                    }
                    get_spboot_port_run = true;
                    if (!sdir.EndsWith("/"))
                    {
                        sdir += "/";
                    }
                    string serverxml = string.Format("{0}{1}/src/main/resources/config/application-dev.yml", sdir, appname);
                    string targetxml = MainForm.TEMP_DIR + string.Format("application-dev-{0}.yml", DateTime.Now.ToString("MMddHHmmss"));
                    targetxml = targetxml.Replace("\\", "/");
                    parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        string port = "", ctx = "";
                        string yml = YSTools.YSFile.readFileToString(targetxml);
                        if(!string.IsNullOrWhiteSpace(yml)){
                            string[] lines = yml.Split('\n');
                            bool find = false;                            
                            int index = 0, start = 0;
                            foreach(string line in lines){
                                if (line.Trim().StartsWith("server:"))
                                {
                                    find = true;
                                    start = index;
                                }
                                else if(find && line.Trim().StartsWith("port:")){
                                    port = line.Substring(line.IndexOf(":") + 1).Trim();
                                }
                                else if (find && line.Trim().StartsWith("context-path:"))
                                {
                                    ctx = line.Substring(line.IndexOf(":") + 1).Trim();
                                }
                                if (index - start > 4 && start > 0)
                                {
                                    break;
                                }
                                index++;
                            }
                        }

                        if (port != "")
                        {
                            stb_home_url.BeginInvoke((MethodInvoker)delegate()
                            {
                                stb_home_url.Text = string.Format("http://{0}:{1}{2}", config.Host, port, ctx);
                            });
                        }
                        
                        get_spboot_port_run = false;

                        File.Delete(targetxml);
                    });
                }
                catch(Exception ex) {
                    logger.Error("Error", ex);
                }

            }
        }

19 View Source File : Job.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static void StartNew(WaitCallback waitCallback,Token token=null)
        {
            ThreadPool.QueueUserWorkItem(state=> {

                if (null!= waitCallback)
                {
                    JobState jobState = new JobState();
                    jobState.Token = token ?? new Token();
                    jobState.State = state;

                    waitCallback.Invoke(jobState);
                }

            });
        }

19 View Source File : TomcatMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void runTaskShell(CmdShell cmds, TaskShell task)
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {

                string shdir = itemConfig.tomcat.TomcatDir;
                if (null != shdir)
                {
                    if (!shdir.EndsWith("/"))
                    {
                        shdir += "/";
                    }
                }

                string shell = task.Shell;
                if (shell.Contains("{tomcat_dir}"))
                {
                    shell = shell.Replace("{tomcat_dir}", shdir);
                }

                if (shell.Contains("{tomcat_webapps}"))
                {
                    shell = shell.Replace("{tomcat_webapps}", shdir + "webapps/");
                }

                if (shell.Contains("{tomcat_logs}"))
                {
                    shell = shell.Replace("{tomcat_logs}", shdir + "logs/");
                }

                if (shell.Contains("{tomcat_startup}"))
                {
                    shell = shell.Replace("{tomcat_startup}", shdir + "bin/startup.sh");
                }

                if (shell.Contains("{tomcat_shutdown}"))
                {
                    shell = shell.Replace("{tomcat_shutdown}", shdir + "bin/shutdown.sh");
                }
                
                shell = shell.Replace("//", "/");

                monitorForm.RunShell(shell, false);
            });
        }

19 View Source File : ByteBuffer.cs
License : MIT License
Project Creator : a1q123456

private void InvokeContinuation(Action<object> continuation, object state, bool forceAsync)
            {
                if (continuation == null)
                    return;

                object scheduler = this.scheduler;
                this.scheduler = null;
                if (scheduler != null)
                {
                    if (scheduler is SynchronizationContext sc)
                    {
                        sc.Post(s =>
                        {
                            var t = (Tuple<Action<object>, object>)s;
                            t.Item1(t.Item2);
                        }, Tuple.Create(continuation, state));
                    }
                    else
                    {
                        Debug.replacedert(scheduler is TaskScheduler, $"Expected TaskScheduler, got {scheduler}");
                        Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, (TaskScheduler)scheduler);
                    }
                }
                else if (forceAsync)
                {
                    ThreadPool.QueueUserWorkItem(continuation, state, preferLocal: true);
                }
                else
                {
                    continuation(state);
                }
            }

19 View Source File : IceMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void StartCheckItems()
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    foreach (ListViewItem item in projects.Items)
                    {
                        CheckItem(item.Text, item);
                    }
                });
            });
        }

19 View Source File : ConfigWindow.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private void CheckVersion()
        {
            verServer.Text = "<< Loading... >>";
            btnRefr.Enabled = btnDl.Enabled = false;
            ThreadPool.QueueUserWorkItem(_ =>
            {
                var sys = new KoiSystem();
                string ver;
                if(string.IsNullOrEmpty(KoiInfo.settings.KoiID))
                {
                    ver = "<< Enter your Koi ID >>";
                }
                else
                {
                    ver = sys.GetVersion(KoiInfo.settings.KoiID);
                    ver = ver ?? "<< Fail to retrieve version >>";
                }
                BeginInvoke(new Action(() =>
                {
                    verServer.Text = ver;
                    btnRefr.Enabled = btnDl.Enabled = true;
                }));
            });
        }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void StartL2R()
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {
                localToRemoteRun = true;
                if (localQueue.Count > 0)
                {
                    while (localToRemoteRun)
                    {
                        try
                        {
                            if (!transfering)
                            {
                                Thread.Sleep(100);
                                RunLocalToRemote();
                            }                            
                        }
                        catch { }
                        Thread.Sleep(100);
                    }
                }                
                localToRemoteRun = false;
            });
        }

19 View Source File : DeviceManager.cs
License : MIT License
Project Creator : aguang-xyz

private void FireCurrentDeviceChangedLater(IDeviceAccessor currentDevice)
        {
            ThreadPool.QueueUserWorkItem(_ =>
            {
                OnCurrentDeviceChanged?.Invoke(this, new CurrentDeviceChangedEvent(currentDevice));
            });
        }

19 View Source File : ControlUtil.cs
License : Apache License 2.0
Project Creator : 214175590

public static void delayHide(Control control, int millis)
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {
                control.BeginInvoke((MethodInvoker)delegate()
                {
                    Thread.Sleep(millis);

                    control.Visible = false;
                });
            });            
        }

19 View Source File : MediaManager.cs
License : MIT License
Project Creator : aguang-xyz

private async Task<IEnumerable<Episode>> GetEpisodesAsync(IMediaProvider provider, string word)
        {
            try
            {
                var url = $"http://light-player/media/{provider.ProviderId}/episodes.json?word={word}";
                var cacheFileName = PathUtils.GetCacheFileName("json", url);
                
                // Try to load episodes from cache first.
                var cachedEpisodes = await ReadJsonAsync<Episode[]>(cacheFileName);
                if (cachedEpisodes != null)
                {
                    // If the cache is older than 10 minutes ago, we will trigger an refresh.
                    if (File.GetLastWriteTime(cacheFileName) < DateTime.Now.AddMinutes(10))
                    {
                        ThreadPool.QueueUserWorkItem(async _ =>
                        {
                            await WriteJsonAsync(cacheFileName, (await provider.GetEpisodesAsync(word)).ToArray());
                        });
                    }

                    return cachedEpisodes;
                }
                
                // If not hint the cache, load from remote. 
                var episodes = (await provider.GetEpisodesAsync(word)).ToArray();

                await WriteJsonAsync(cacheFileName, episodes);

                return episodes;
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "Failed to get episodes for {ProviderId} - {Word}", provider.ProviderId, word);
                return Array.Empty<Episode>();
            }
        }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void createRemoteDir(string remotePath, CreateLinuxDirCallback callback)
        {
            try
            {
                string dir = Utils.getLinuxPathDir(remotePath);
                if (remote_path != dir)
                {
                    rightForm.SendShell("mkdir -p " + dir);
                    remote_path = dir;
                    ThreadPool.QueueUserWorkItem((a) => {
                        if (null != callback)
                        {
                            Thread.Sleep(300);
                            callback();
                        }
                    });                    
                }
                else if (null != callback)
                {
                    callback();
                }
            }
            catch { }
        }

19 View Source File : SpringBootMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void runTaskShell(CmdShell cmds, TaskShell task)
        {
            ThreadPool.QueueUserWorkItem((a) => { 

                string shdir = itemConfig.spring.ShFileDir;
                if (null != shdir)
                {
                    if (!shdir.EndsWith("/"))
                    {
                        shdir += "/";
                    }
                }

                string shell = task.Shell;
                if (shell.Contains("{sh_bin_dir}"))
                {
                    shell = shell.Replace("{sh_bin_dir}", shdir);
                }

                if (shell.Contains("{project_dir}"))
                {
                    shell = shell.Replace("{project_dir}", l_source_path.Text);
                }

                if (shell.Contains("{build_sh_file}"))
                {
                    shell = shell.Replace("{build_sh_file}", itemConfig.spring.BuildFileName);
                }

                if (shell.Contains("{ctl_sh_file}"))
                {
                    shell = shell.Replace("{ctl_sh_file}", itemConfig.spring.CrlFileName);
                }
                shell = shell.Replace("//", "/");

                monitorForm.RunShell(shell, false);
            });
        }

19 View Source File : CelesteNetClientRC.cs
License : MIT License
Project Creator : 0x0ade

private static void ListenerLoop() {
            Logger.Log(LogLevel.INF, "rc", $"Started ClientRC thread, available via http://localhost:{CelesteNetUtils.ClientRCPort}/");
            try {
                while (Listener?.IsListening ?? false) {
                    ThreadPool.QueueUserWorkItem(c => {
                        HttpListenerContext context = c as HttpListenerContext;

                        if (context.Request.HttpMethod == "OPTIONS") {
                            context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
                            context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                            context.Response.AddHeader("Access-Control-Max-Age", "1728000");
                            return;
                        }
                        context.Response.AppendHeader("Access-Control-Allow-Origin", "*");

                        try {
                            using (context.Request.InputStream)
                            using (context.Response) {
                                HandleRequest(context);
                            }
                        } catch (ThreadAbortException) {
                            throw;
                        } catch (ThreadInterruptedException) {
                            throw;
                        } catch (Exception e) {
                            Logger.Log(LogLevel.INF, "rc", $"ClientRC failed responding: {e}");
                        }
                    }, Listener.GetContext());
                }
            } catch (ThreadAbortException) {
                throw;
            } catch (ThreadInterruptedException) {
                throw;
            } catch (HttpListenerException e) {
                // 500 = Listener closed.
                // 995 = I/O abort due to thread abort or application shutdown.
                if (e.ErrorCode != 500 &&
                    e.ErrorCode != 995) {
                    Logger.Log(LogLevel.INF, "rc", $"ClientRC failed listening ({e.ErrorCode}): {e}");
                }
            } catch (Exception e) {
                Logger.Log(LogLevel.INF, "rc", $"ClientRC failed listening: {e}");
            }
        }

19 View Source File : ConditionTaskForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void init()
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    string json = YSTools.YSFile.readFileToString(MainForm.CONF_DIR + "shell_temp.json");
                    JObject obj = JsonConvert.DeserializeObject<JObject>(json);

                    conditionTemp = (JObject)obj["condition_temp"];                    

                    JObject shellTemp = (JObject)obj["task_shell_temp"][typeArr[index]];
                    if (null != shellTemp)
                    {
                        ListViewItem item = null;
                        ListViewItem.ListViewSubItem subItem = null;
                        foreach (var o in shellTemp)
                        {
                            item = new ListViewItem();
                            item.Tag = o;
                            item.Text = o.Key;

                            subItem = new ListViewItem.ListViewSubItem();
                            subItem.Text = o.Value.ToString();

                            item.SubItems.Add(subItem);
                            scb_template.Items.Add(item);
                        }
                    }

                    JArray varsTemp = (JArray)obj["vars_temp"][typeArr[index]];
                    if (null != varsTemp)
                    {
                        ListViewItem item = null;
                        ListViewItem.ListViewSubItem subItem = null;
                        foreach (var o in varsTemp)
                        {
                            item = new ListViewItem();
                            item.Tag = o;
                            item.Text = o["value"].ToString();

                            subItem = new ListViewItem.ListViewSubItem();
                            subItem.Text = o["desc"].ToString();

                            item.SubItems.Add(subItem);
                            var_list.Items.Add(item);
                        }
                    }

                });
            });
        }

19 View Source File : NginxMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void runTaskShell(CmdShell cmds, TaskShell task)
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {

                string shdir = itemConfig.nginx.NginxPath;
                if (null != shdir)
                {
                    if (shdir.EndsWith("/"))
                    {
                        shdir = shdir.Substring(0, shdir.Length - 1);
                    }
                    shdir = shdir.Substring(0, shdir.LastIndexOf("/") + 1);
                }

                string shell = task.Shell;
                if (shell.Contains("{nginx_dir}"))
                {
                    shell = shell.Replace("{nginx_dir}", shdir);
                }

                if (shell.Contains("{nginx}"))
                {
                    shell = shell.Replace("{nginx}", itemConfig.nginx.NginxPath);
                }

                shell = shell.Replace("//", "/");

                monitorForm.RunShell(shell, false);
            });
        }

19 View Source File : TimedTaskForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void init()
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    string json = YSTools.YSFile.readFileToString(MainForm.CONF_DIR + "shell_temp.json");
                    JObject obj = JsonConvert.DeserializeObject<JObject>(json);
                    JObject shellTemp = (JObject)obj["task_shell_temp"][typeArr[index]];
                    if (null != shellTemp)
                    {
                        ListViewItem item = null;
                        ListViewItem.ListViewSubItem subItem = null;
                        foreach (var o in shellTemp)
                        {
                            item = new ListViewItem();
                            item.Tag = o;
                            item.Text = o.Key;

                            subItem = new ListViewItem.ListViewSubItem();
                            subItem.Text = o.Value.ToString();

                            item.SubItems.Add(subItem);
                            scb_template.Items.Add(item);
                        }
                    }

                    JArray varsTemp = (JArray)obj["vars_temp"][typeArr[index]];
                    if (null != varsTemp)
                    {
                        ListViewItem item = null;
                        ListViewItem.ListViewSubItem subItem = null;
                        foreach (var o in varsTemp)
                        {
                            item = new ListViewItem();
                            item.Tag = o;
                            item.Text = o["value"].ToString();

                            subItem = new ListViewItem.ListViewSubItem();
                            subItem.Text = o["desc"].ToString();

                            item.SubItems.Add(subItem);
                            var_list.Items.Add(item);
                        }
                    }

                });
            });
        }

19 View Source File : SftpWinForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void renameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int count = listView1.SelectedItems.Count;
            if (count == 1)
            {
                ListViewItem item = listView1.SelectedItems[0];
                Object tag = item.Tag;
                string msg = "请输入文件夹的新名称";
                if (tag is FileInfo)
                {
                    msg = "请输入文件的新名称";
                }
                string oldName = item.Text;
                InputForm form = new InputForm(msg, oldName, new InputForm.FormResult((newName) =>
                {
                    if (oldName != newName)
                    {
                        string dirs = getCurrDir();
                        string path1 = dirs + oldName;
                        string path2 = dirs + newName;
                        if (tag is FileInfo)
                        {
                            FileInfo file = new FileInfo(path2);
                            if (!file.Exists)
                            {
                                new FileInfo(path1).MoveTo(path2);
                            }
                        }
                        else if (tag is DirectoryInfo)
                        {
                            DirectoryInfo dire = new DirectoryInfo(path2);
                            if (!dire.Exists)
                            {
                                new DirectoryInfo(path1).MoveTo(path2);
                            }
                        }

                        ThreadPool.QueueUserWorkItem((a) =>
                        {
                            Thread.Sleep(500);
                            RefreshFiles();
                        });
                    }
                }));
                form.ShowDialog(this);
            }  
        }

See More Examples