2017-07-21 48 views
0

我使用Cefsharp.Winform(http://cefsharp.github.io/)。 我嘗試Form.Close()但它的錯誤: System.InvalidOperationException:'跨線程操作無效:控制'Form2'從一個線程訪問,而不是它創建的線程'。錯誤:當使用CefSharp的Form.close()時出現「跨線程操作無效」

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; 

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

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

Form2.cs

using CefSharp; 
using CefSharp.WinForms; 
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; 

namespace TEST_CEF 
{ 
    public partial class Form2 : Form 
    { 
     public Form2() 
     { 
      InitializeComponent(); 
      InitBrowser(); 

     } 

     public ChromiumWebBrowser browser; 
     public void InitBrowser() 
     { 
      Cef.Initialize(new CefSettings()); 
      browser = new ChromiumWebBrowser("www.google.com"); 
      this.Controls.Add(browser); 
      browser.Dock = DockStyle.Fill; 

      browser.FrameLoadEnd += WebBrowserFrameLoadEnded; 
     } 

     private void WebBrowserFrameLoadEnded(object sender, FrameLoadEndEventArgs e) 
     { 
      if (e.Frame.IsMain) 
      { 
       if (browser.Address.IndexOf("google") > -1) 
       { 
        timer1.Start(); 
       } 
      } 
     } 

     private void Form2_FormClosing(object sender, FormClosingEventArgs e) 
     { 
      browser.Dispose(); 
      Cef.Shutdown(); 
     } 
     int time = 0; 
     private void timer1_Tick(object sender, EventArgs e) 
     { 
      time++; 
      if (time==3) 
      { 
       this.Close(); 
      } 
     } 
    } 
} 

回答

0

你使用哪種類型的計時器? 考慮在timer1_Tick方法中使用InvokeRequired。

private void timer1_Tick(object sender, EventArgs e) 
{ 
    if (InvokeRequired) { Invoke(new Action(() => { timer1_Tick(sender, e); })); return; } 

    time++; 
    if (time==3) 
    { 
     this.Close(); 
    } 
} 
0

docs(重點從我):

It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI thread. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang.. To access UI elements you'll need to Invoke/Dispatch onto the UI Thread.

所以,你開始在另一個線程的計時器,所以我想在Tick活動將在此CEF UI線程提高了。

所以,如果需要的話,你必須使用Invoke

Action close =() => this.Close(); 
if (InvokeRequired) 
    Invoke(close); 
else 
    close();