Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 跨线程操作无效,正在尝试找到解决方案_C# - Fatal编程技术网

C# 跨线程操作无效,正在尝试找到解决方案

C# 跨线程操作无效,正在尝试找到解决方案,c#,C#,它执行@RefreshDataGrid()很好,但当我尝试执行findCommand()时,它会出现以下异常: 引发异常:System.Windows.Forms.dll中的“System.InvalidOperationException” 跨线程操作无效:从创建控件的线程以外的线程访问控件“dgvMySqlKBer” 如果你需要更多的信息,请随意询问,无论如何,这是代码。 我发现它与:this.Load+=Form1\u Load using System; using System.Thr

它执行@RefreshDataGrid()很好,但当我尝试执行findCommand()时,它会出现以下异常:

引发异常:System.Windows.Forms.dll中的“System.InvalidOperationException” 跨线程操作无效:从创建控件的线程以外的线程访问控件“dgvMySqlKBer”

如果你需要更多的信息,请随意询问,无论如何,这是代码。 我发现它与:
this.Load+=Form1\u Load

using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using Discord;
using System.Media;
using System.Text.RegularExpressions;
using System.Data;
using System.ComponentModel;
using MySql.Data.MySqlClient;
using System.Linq;

namespace DiscordSongRequest
{
    public partial class Form1 : Form
    {
        string ipaddress = "localhost";
        string username = "root";
        string password = "";

        private DiscordClient client;
        SoundPlayer player = new SoundPlayer();
        Random random = new Random();
        public static readonly Regex YoutubeVideoRegex = new Regex(@"youtu(?:\.be|be\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)", RegexOptions.IgnoreCase);

        public Form1()
        {
            this.Load += Form1_Load;
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {
            Task.Factory.StartNew(() => ConnectClient());
            InitializeComponent();            
            dgvMySqlKBer.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            RefreshDataGrid();
        }

        private void RefreshDataGrid()
        {
            try
            {
                string MyConnection = "datasource=" + ipaddress + ";username=" + username + ";password=" + password + "";
                string Query = "select * from discordsongrequest.commands;";
                MySqlConnection MyConn = new MySqlConnection(MyConnection);
                MySqlCommand MyCommand = new MySqlCommand(Query, MyConn);
                MyConn.Open();
                MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
                MyAdapter.SelectCommand = MyCommand;
                DataTable dTable = new DataTable();
                MyAdapter.Fill(dTable);
                dgvMySqlKBer.DataSource = dTable;            
                MyConn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private async Task ConnectClient()
        {
            try
            {
                client = new DiscordClient();
                client.MessageCreated += async (s, e) =>
                {
                    switch (e.Message.Text)
                    {
                        case "!stop":
                            webBrowser1.Navigate("about:blank");
                            break;
                        case "!hallo":
                            findCommand(e.Message.Text);
                            player.Play();
                            break;                        
                        case "!play":
                            break;
                        case "!random":
                            int randomNumber = random.Next(0, 1000);
                            await client.SendMessage(e.Message.Channel, "Random! You roll a: " + Convert.ToString(randomNumber) + ".");
                            break;
                        case "!coin":
                            randomNumber = random.Next(0, 2);
                            if (randomNumber == 0)
                            {
                                await client.SendMessage(e.Message.Channel, "Coinflip! it lands on: Heads.");
                            }
                            else
                            {
                                await client.SendMessage(e.Message.Channel, "Coinflip! it lands on: Tails.");
                            }
                            break;
                        default:
                            if (e.Message.Text.StartsWith("!play"))
                            {
                                string l = e.Message.Text;
                                l = (l.StartsWith("!play")) ? l.Substring(6) : l;
                                checkForLink(l);
                            }
                            break;
                    }
                };
                await client.Connect("username", "password");
                await client.AcceptInvite("invitecode");
            }

            catch
            {
            }
        }

        private void checkForLink(string l)
        {
            try
            {
                Match youtubeMatch = YoutubeVideoRegex.Match(l);
                if (youtubeMatch.Success)
                {
                    Uri uri = new Uri(l);
                    webBrowser1.Url = uri;
                }
            }

            catch
            {
            }
        }

        private void findCommand(string command)
        {            
            string MyConnection = "datasource=" + ipaddress + ";username=" + username + ";password=" + password + "";
            string Query = "select * from discordsongrequest.commands where command = '" + command + "';";
            MySqlConnection MyConn = new MySqlConnection(MyConnection);
            MySqlCommand MyCommand = new MySqlCommand(Query, MyConn);
            MyConn.Open();
            MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
            MyAdapter.SelectCommand = MyCommand;
            DataTable dTable = new DataTable();
            MyAdapter.Fill(dTable);
            dgvMySqlKBer.DataSource = dTable;
            MyConn.Close();
        }

    }
}
请看这里:

dgvMySqlKBer对象是在主事件线程中创建的,您试图从另一个线程中访问它,这不是一个有效的操作。您需要在该对象中调用invoke并向其传递操作

    private void findCommand(string command)
    {            
        string MyConnection = "datasource=" + ipaddress + ";username=" + username + ";password=" + password + "";
        string Query = "select * from discordsongrequest.commands where command = '" + command + "';";
        MySqlConnection MyConn = new MySqlConnection(MyConnection);
        MySqlCommand MyCommand = new MySqlCommand(Query, MyConn);
        MyConn.Open();
        MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
        MyAdapter.SelectCommand = MyCommand;
        DataTable dTable = new DataTable();
        MyAdapter.Fill(dTable);

        dgvMySqlKBer.Invoke((MethodInvoker)delegate
        {
            dgvMySqlKBer.DataSource = dTable;
        });         

        dgvMySqlKBer.DataSource = dTable;
        MyConn.Close();
    }

请停止标记此帖子以引起版主注意,并要求版主从帖子中删除否决票。主持人不能改变投票结果。好吧,这个过程出了问题,不是吗?你怎么会这么想?堆栈溢出允许用户随心所欲地投票(前提是投票不是欺诈性的或有针对性的;这里也不适用)。投票应该代表社会的共识;不是一个主持人的感觉。如果我们允许主持人随意取消投票,我们将失去这一观点。你说得有道理,但如果这个答案是正确的,而它的评级是负面的,那么这个答案又如何帮助任何人呢?如果你关注这些评论,你会发现我更新了答案,而且评分一直是否定的。。。不管怎样,我明白你的意思了。@Marco这个答案是错的。使用
async/await
时,不需要
BeginInvoke
(调用块)。出现此问题的原因是OP试图从后台线程内部访问控件。数据访问代码正试图修改UI,这是一个糟糕的设计。应该重构代码,将结果返回给可以更新UI的异步事件处理程序