[当使用RestSharp方法时,Visual Studio中断

问题描述 投票:0回答:2

我有一个很奇怪的问题,今天早些时候,我在Visual Studio中运行并运行了大量代码,我的表单运行得很完美。我去吃午饭回来了,试图打开它,什么也没有。它运行,有0个错误,它使用内存,但不会显示该表单。据我所知,我尚未进行任何更改。

我创建了一个新的Windows窗体应用程序,并逐行重新编写了代码,我发现了破坏它的原因,但是我一生都无法弄清为什么会破坏它。

Form1.cs损坏

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RestSharp;
using Newtonsoft;
using Newtonsoft.Json;

namespace RestApiViewerWUG
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var client = new RestClient("http://notrelevent.whocares.com/api/v1/token");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Authorization", "Basic cmVzdDo5RGJSIypkQDQ=");
            request.AddHeader("Content-Type", "text/plain");
            request.AddParameter("text/plain", "userName=rest&password=xxxxxx&grant_type=password", ParameterType.RequestBody); 
            IRestResponse response = client.Execute(request); //THIS LINE BREAKS IT

            }

            private void Form1_Load(object sender, EventArgs e)
            {

            }

            private void textBox1_TextChanged(object sender, EventArgs e)
            {

            }
    }
}

问题

只需删除“ IRestResponse response = client.Execute(request);”行。修复它并允许表单出现。

我尝试了什么?

  • 我已确保正确安装和引用RestSharp,我已经甚至尝试了几个版本。
  • 我已卸载并重新安装了Visual Studio 2015
  • 如上所述,我已经逐行创建了一个全新的项目
  • 断点/写入控制台/日志不执行任何操作,当代码中的那一行保留为0时,将发生任何事情

其他信息

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RestApiViewerWUG
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

表格:

从字面上看只是具有精确名称为textBox1的textBox

c# winforms visual-studio-2015 restsharp
2个回答
3
投票

简短的说,您不应该在constructor中执行此类操作,而是在加载表单后执行。

然后,如果存在超时,则无需等待表单加载,并且可以反馈正在进行中的事实,或者如果存在exception,则不会撕裂表单。 form向下。

您还将捕获任何exceptions,并提供一些有关可能发生的故障模式的通知。

背景

A表单constructor在加载(呈现)表单之前运行,因此最好不要在其中进行任何昂贵的操作,实际上这对于任何构造函数都是正确的。构造函数用于初始化类/结构需要运行的最低状态。

关于表单constructor,如果在构造函数期间发生了长期运行的过程,则将直接影响表单加载,并且不会显示出让用户(和您)挠头的意思。没有显示。更糟糕的是,如果存在unhandeled exception,则您的表单将永远无法加载


0
投票

我对此深表歉意,并感谢我学到的新知识。

我的问题的答案太简单了……一个月前,我向我们的api添加了一个证书,但是它似乎从未适用,其他人抱怨我们在服务器上使用的产品存在类似问题。我什么都没想到。

昨天,他们使服务器脱机了几分钟,以替换PSU,重新启动后...我的证书已加载,因此现在使用https。

之所以不会“加载”,实际上是因为服务器的超时时间大约需要60秒,因此在等待足够长的时间后才会填充。

© www.soinside.com 2019 - 2024. All rights reserved.