背景工作的问题 [英] problem with background work

查看:46
本文介绍了背景工作的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public string HttpGet(string URI)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URI);
            req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            
            req.Accept = "*/*";
            req.Headers.Add("UA-CPU", "x86");
            req.Headers.Add("Accept-Language", "en-us");
            req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2;  SV1; .NET CLR 1.1.4322)";
            
           
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            
            //Read all headers from the response & Request
            WebHeaderCollection ResponseHeader = resp.Headers;
            WebHeaderCollection RequestHeader = req.Headers;
            StreamReader sr = new StreamReader(resp.GetResponseStream());

            string s = URI;
            string s1 = req.RequestUri + " / " + (int)resp.StatusCode + " / " + resp.StatusDescription + Environment.NewLine + ResponseHeader.ToString() + sr.ReadToEnd();
            string s2 = req.RequestUri + " /" + req.Method + " / " + req.ProtocolVersion + " / " + Environment.NewLine + RequestHeader.ToString();

            NetworkMonitor(s, s1, s2);
            
            return s1.Trim();

        }


private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
           // startextraction();
            
            BackgroundWorker worker = (BackgroundWorker)sender;
            try
            {
                using (StreamReader reader = new StreamReader("F://testing.txt"))
                {
                    int out_count = 0;
                    int out_count_1 = 0;
                    int out_count_2 = 0;
                    int row_count = 0;

                    DataTable table = new DataTable();
                    foreach (DataRow rw in table_1.Rows)
                    {
                        table.Columns.Add(rw[0].ToString());
                    }
                    string input;
                    int i = 0;
                  
                    while ((input = reader.ReadLine()) != null)
                    {
                        string sourcecode = HttpGet(input);
                        worker.ReportProgress(i);

                        //string sourcecode = HttpPost(input, PostRaw);

                        //run_logs.AppendText("[Traversed] " + input + DateTime.Now.ToString());
                        //run_logs.AppendText(Environment.NewLine);
                        //run_logs.Update();
                       
                        // Here we check the Match instance.

                        foreach (DataRow row in table_1.Rows)
                        {
                            int index = table_1.Rows.IndexOf(row);

                            //Here we call Regex.Match.
                            Match match = Regex.Match(sourcecode, row[1].ToString(), RegexOptions.IgnoreCase);
                            int count = 0;
                            while (match.Success)
                            {
                                // Finally, we get the Group value and display it.
                                if (index == 0)
                                {
                                    table.Rows.Add(match.Groups[Convert.ToInt32(row[2].ToString())].Value);
                                    row_count++;
                                }
                                else if (index == 1)
                                {
                                    try
                                    {
                                        table.Rows[out_count][index] = match.Groups[Convert.ToInt32(row[2].ToString())].Value;
                                    }
                                    catch
                                    {
                                        table.Rows.Add();
                                    }
                                    finally
                                    {
                                        table.Rows[out_count][index] = match.Groups[Convert.ToInt32(row[2].ToString())].Value;
                                    }
                                    out_count++;
                                }
                                else if (index == 2)
                                {
                                    try
                                    {
                                        table.Rows[out_count_1][index] = match.Groups[Convert.ToInt32(row[2].ToString())].Value;
                                    }
                                    catch
                                    {
                                        table.Rows.Add();
                                    }
                                    finally
                                    {
                                        table.Rows[out_count_1][index] = match.Groups[Convert.ToInt32(row[2].ToString())].Value;
                                    }
                                    out_count_1++;
                                }
                                else if (index == 3)
                                {
                                    try
                                    {
                                        table.Rows[out_count_2][index] = match.Groups[Convert.ToInt32(row[2].ToString())].Value;
                                    }
                                    catch
                                    {
                                        table.Rows.Add();
                                    }
                                    finally
                                    {
                                        table.Rows[out_count_2][index] = match.Groups[Convert.ToInt32(row[2].ToString())].Value;
                                    }
                                    out_count_2++;
                                }
                                else
                                {

                                }
                                count++;
                                match = match.NextMatch();
                            }

                          //  run_logs.AppendText("[REGEX] " + regex + " Extracted " + count + " Matches");
                           // run_logs.AppendText(Environment.NewLine);
                            
                        }
                        //toolStripProgressBar1.Maximum = 4;
                        //toolStripProgressBar1.Value = toolStripProgressBar1.Value + 1;
                       // run_logs.Update();
                        dataGridView1.DataSource = table;
                        dataGridView1.Update();
                        dataGridView1.FirstDisplayedScrollingRowIndex = row_count;
                        
                    }

                }
            }
            catch (Exception hg)
            {
                MessageBox.Show(hg.Message);

            }
        }

推荐答案

引用:

问题是跨线程操作无效:控制'dataGridView1'从其创建的线程以外的线程访问

the problem is Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on

这是一个众所周知的问题,你可能会找到很多信息只需谷歌搜索。更多, Microsoft 轻轻地提供解决它的指导方针:如何:对Windows窗体控件进行线程安全调用 [ ^ ]。

This is a well-know problem, you may find a lot of info just Googling for. Morevover, Microsoft gently provides the guidelines for solving it: How to: Make Thread-Safe Calls to Windows Forms Controls[^].


将结果分配给e.result并更新UI RunWorkerCompleted。



private void backgroundWorker1_DoWork(object sender,

DoWorkEventArgs e)

{



//您的密码











//将结果DataTable表分配给_DoWork

//中的e.Result到DoWorkEventArgs的Result属性
//对象。这将是

// RunWorkerCompleted事件处理程序。

e.Result = table;

}



//这个事件处理程序处理

//后台操作的结果。

private void backgroundWorker1_RunWorkerCompleted(

对象发件人,RunWorkerCompletedEventArgs e)

{

//首先,处理案例抛出异常的地方。

如果(e.Error!= null)

{

//处理错误

MessageBox.Show( e.Error.Message);

}

else if(e.Cancelled)

{

//接下来,处理用户取消

//操作的情况。

//请注意,由于在
// DoWork事件处理程序中的竞争条件,可能没有取消

//标记设置,即使

//已经调用CancelAsync。





}

else

{

//最后,处理操作

//成功的情况。

DataTable table =(DataTable)e.Result;



dataGridView1.DataSource = table;

dataGridView1.Update();

dataGridView1.FirstDisplayedScrollingRowIndex = table.Rows.Count;

}



}
Assign the result to e.result and update the UI in RunWorkerCompleted.

private void backgroundWorker1_DoWork(object sender,
DoWorkEventArgs e)
{

//Your code
.
.
.
.

// Assign the result DataTable table to e.Result in _DoWork
// to the Result property of the DoWorkEventArgs
// object. This is will be available to the
// RunWorkerCompleted eventhandler.
e.Result = table;
}

// This event handler deals with the results of the
// background operation.
private void backgroundWorker1_RunWorkerCompleted(
object sender, RunWorkerCompletedEventArgs e)
{
// First, handle the case where an exception was thrown.
if (e.Error != null)
{
// Handle Error
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
// Next, handle the case where the user canceled
// the operation.
// Note that due to a race condition in
// the DoWork event handler, the Cancelled
// flag may not have been set, even though
// CancelAsync was called.


}
else
{
// Finally, handle the case where the operation
// succeeded.
DataTable table= (DataTable) e.Result;

dataGridView1.DataSource = table;
dataGridView1.Update();
dataGridView1.FirstDisplayedScrollingRowIndex = table.Rows.Count;
}

}


这篇关于背景工作的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆