为什么我得到异常StackOverFlowException?以及如何解决它?

时间:2015-06-17 14:11:47

标签: c# .net winforms

我在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时,它将首先显示新表单,然后以新表单执行代码。

2 个答案:

答案 0 :(得分:5)

看看这一行:

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

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

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

将行更改为:

this.Run().Wait();

答案 1 :(得分:4)

更改行

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

Run().Wait();

从构造函数中调用构造函数。我认为你可能仍然会遇到问题,因为你在显示表单之前从构造函数调用方法,但是一次只能做一件事。