异步方法和事件

时间:2015-08-21 06:23:25

标签: c# events asynchronous awesomium

我使用awesomium来自动化网站。我试图使用异步编程,因为我不希望我的GUI冻结,但我在一个事件中遇到问题(弹出窗口出现,我想在这个弹出窗口中做一些操作,直到我关闭它)没有继续我想要的。在事件被触发之后,我希望我的应用程序继续使用事件方法(webc_ShowCreatedWebView和之后的popupTwitter(方法),但我发现在执行JavaScript代码时,控件从第一个方法返回While。我怎么能这样做在调用earnpoints方法并触发事件以完成事件和方法之后,控件将在此时返回。

  private async void button4_Click(object sender, EventArgs e)
    {
        Twitter twitter = new Twitter(webView);
        twitter.Login(webView);
        webView.ShowCreatedWebView += webc_ShowCreatedWebView;
        addmefast.Login(webView);
        int i = 0;
        while (i < 10)
        {
            Task earnpoints = EarnPoints(webView);
            await earnpoints;
            //Here i don't want to continue until EarnPoints method > webc_ShowCreatedWebView event > popupTwitter method it's finished.
            i++;
        }
    }

    public async Task EarnPoints(IWebView web)
    {
        web.Source = "http://addmefast.com/free_points/twitter".ToUri();
        await Task.Delay(3000);
        web.ExecuteJavascript("document.getElementsByClassName('single_like_button btn3-wrap')[0].click();"); //event fired: webc_ShowCreatedWebView
    }

    async void webc_ShowCreatedWebView(object sender, ShowCreatedWebViewEventArgs e)
    {
        WebView view = new WebView(e.NewViewInstance);
        await popupTwitter(view);
    }

   async Task popupTwitter(WebView view)
    {
        Popupform FormTwitter = new Popupform(view);
        FormTwitter.Show();
       await  Task.Delay(6000);
        FormTwitter.Twitter();
        await Task.Delay(2000);
        FormTwitter.Close();
        await  Task.Delay(4000);
    }

1 个答案:

答案 0 :(得分:1)

我在使用awesomium实现异步方法时也遇到了问题,但是让它工作了。

首先我制作了这个包装器。必须在主线程上创建。

public class AsyncWebView
{

    public static SynchronizationContext _synchronizationContext;
    private readonly WebView _webView;

    public AsyncWebView()
    {
        _synchronizationContext = SynchronizationContext.Current;

        _webView = WebCore.CreateWebView(1024, 900);
    }

    public async Task Navigate(String url)
    {
        Debug.WriteLine("Navigating");
        TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

        FrameEventHandler handler = (sender, args) =>
        {
            Debug.WriteLine(args.Url);

            if (!_webView.IsNavigating && !_webView.IsLoading)
                tcs.SetResult(true);
        };

        _webView.LoadingFrameComplete += handler;

        _synchronizationContext.Send(SetWebViewSource, url);

        await tcs.Task;

        _webView.LoadingFrameComplete -= handler;

        Debug.WriteLine("Done");

    }

    private void SetWebViewSource(object url)
    {
        _webView.Source = new Uri((string)url);
    }
}

用法:

async Task test()
{
    await webView.Navigate("http://www.nytimes.com");
    Debug.WriteLine("All done");
}

确保您有一个SynchronizationContext,其中调用AsyncWebView构造函数。

相关问题