为什么我得到异常 堆栈超流异常 ?以及如何解决它

本文关键字:异常 何解决 解决 堆栈 为什么 | 更新日期: 2023-09-27 17:56:41

我在form1中添加了一个新表单,我有一个按钮单击事件:

private void button1_Click(object sender, EventArgs e)
        {
            UploadTestingForum utf = new UploadTestingForum();
            utf.Show();
        }

我从这里的例子中获取的新表单代码:

https://github.com/youtube/api-samples/blob/master/dotnet/UploadVideo.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 System.IO;
using System.Reflection;
using System.Threading;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
namespace Youtube_Manager
{
    public partial class UploadTestingForum : Form
    {
        string errors = "";
        public UploadTestingForum()
        {
            InitializeComponent();
            try
            {
                new UploadTestingForum().Run().Wait();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    //Console.WriteLine("Error: " + e.Message);
                    errors = e.Message;
                }
            }
        }

        private async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream(@"D:'C-Sharp'Youtube-Manager'Youtube-Manager'Youtube-Manager'bin'Debug'client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                );
            }
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });
            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "Default Video Title";
            video.Snippet.Description = "Default Video Description";
            video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
            var filePath = @"D:'tester'20131207_134823.mp4"; // Replace with path to actual movie file.
            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
                await videosInsertRequest.UploadAsync();
            }
        }
        void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
        {
            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    //Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                    label1.Text = progress.BytesSent.ToString();
                    break;
                case UploadStatus.Failed:
                    //Console.WriteLine("An error prevented the upload from completing.'n{0}", progress.Exception);
                    label1.Text = progress.Exception.ToString();
                    break;
            }
        }
        void videosInsertRequest_ResponseReceived(Video video)
        {
            //Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
            label2.Text = video.Id;
        }
        private void UploadTestingForum_Load(object sender, EventArgs e)
        {
        }
    }
}

但是一旦我单击 form1 按钮,我就会使用断点,我看到它正在执行一个循环,它一直在执行以下行:

string errors = "";new UploadTestingForum().Run().Wait();

然后几秒钟后,我在表单设计器 cs 文件中出现异常:this.ResumeLayout(false);

An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll
System.StackOverflowException was unhandled

我想做的是,当我在 form1 中单击 button1 时,它将首先显示新表单,然后在新表单中执行代码。

为什么我得到异常 堆栈超流异常 ?以及如何解决它

请看这一行:

 new UploadTestingForum().Run().Wait();

请记住,这是窗体构造函数的一部分。当该代码运行时,它会创建窗体的另一个实例并运行其构造函数。此时,您将再次执行相同的代码,这将创建另一个实例并运行其构造函数,该构造函数再次执行此代码,从而创建表单的另一个实例。

每次构造函数运行另一个方法调用时,调用堆栈都会进行。由于您创建了一个新实例并在方法返回之前再次调用构造函数,因此永远不会清除/弹出堆栈条目。很快,调用堆栈就会耗尽空间并溢出,因此会出现 StackOverflowException。

将行更改为:

this.Run().Wait();

更改行

new UploadTestingForum().Run().Wait();

Run().Wait();

从构造函数调用构造函数。我认为在显示表单之前,当您从构造函数调用该方法时,您可能仍然会遇到问题,但一次一件事。