From fe98124c9be900a80472cdacd0eab537ab452022 Mon Sep 17 00:00:00 2001 From: Alex Maitland Date: Sat, 8 Jun 2019 17:21:49 +1000 Subject: [PATCH] Async JavascriptBinding - Add support for returning Task (#2771) * Async JavascriptBinding - Add support for returning Task Remove Parallel Task execution code from MethodRunnerQueue Add ParallelMethodRunnerQueue - For the new code path the Func is executed, if the Result is a generic Task we wait for it's completion - If the task is not generic then we return immediately This is only enabled when CefSharpSettings.ConcurrentTaskExecution = true; * MethodRunnerQueue - Display error message when method returns Task * ParallelMethodRunnerQueue - Rename to ConcurrentMethodRunnerQueue * MethodRunnerQueue - Improve formatting of error message when method returns Task * Async JavascriptBinding Return Task - Add Basic xUnit Test Very quick test, needs to be refined a little. The basics are working as expected. * Add Binding Test Async Task Example to the WPF Example menu * Async JSB Task - Add additional tests and improve error messaging --- CefSharp.Core/ManagedCefBrowserAdapter.cpp | 2 +- CefSharp.Core/ManagedCefBrowserAdapter.h | 17 +- CefSharp.Example/CefExample.cs | 4 +- CefSharp.Example/CefSharp.Example.csproj | 1 + .../CefSharpSchemeHandlerFactory.cs | 3 +- .../JavascriptBinding/AsyncBoundObject.cs | 45 +++++ .../Properties/Resources.Designer.cs | 51 +++-- CefSharp.Example/Properties/Resources.resx | 3 + .../Resources/BindingTestSingle.html | 70 ++++--- .../Resources/BindingTestsAsyncTask.html | 109 ++++++++++ CefSharp.Test/CefSharp.Test.csproj | 5 + .../ConcurrentMethodRunnerQueueFacts.cs | 77 +++++++ CefSharp.Wpf.Example/MainWindow.xaml | 2 + CefSharp.Wpf.Example/MainWindow.xaml.cs | 10 + CefSharp/CefSharp.csproj | 2 + .../Internals/ConcurrentMethodRunnerQueue.cs | 191 ++++++++++++++++++ CefSharp/Internals/IBrowserAdapter.cs | 2 +- CefSharp/Internals/IMethodRunnerQueue.cs | 17 ++ CefSharp/Internals/MethodRunnerQueue.cs | 46 ++--- 19 files changed, 587 insertions(+), 70 deletions(-) create mode 100644 CefSharp.Example/Resources/BindingTestsAsyncTask.html create mode 100644 CefSharp.Test/Framework/ConcurrentMethodRunnerQueueFacts.cs create mode 100644 CefSharp/Internals/ConcurrentMethodRunnerQueue.cs create mode 100644 CefSharp/Internals/IMethodRunnerQueue.cs diff --git a/CefSharp.Core/ManagedCefBrowserAdapter.cpp b/CefSharp.Core/ManagedCefBrowserAdapter.cpp index 7f5e4cf1b..920fc1bec 100644 --- a/CefSharp.Core/ManagedCefBrowserAdapter.cpp +++ b/CefSharp.Core/ManagedCefBrowserAdapter.cpp @@ -140,7 +140,7 @@ JavascriptObjectRepository^ ManagedCefBrowserAdapter::JavascriptObjectRepository return _javaScriptObjectRepository; } -MethodRunnerQueue^ ManagedCefBrowserAdapter::MethodRunnerQueue::get() +IMethodRunnerQueue^ ManagedCefBrowserAdapter::MethodRunnerQueue::get() { return _methodRunnerQueue; } diff --git a/CefSharp.Core/ManagedCefBrowserAdapter.h b/CefSharp.Core/ManagedCefBrowserAdapter.h index c306be90f..b29d6a108 100644 --- a/CefSharp.Core/ManagedCefBrowserAdapter.h +++ b/CefSharp.Core/ManagedCefBrowserAdapter.h @@ -33,7 +33,7 @@ namespace CefSharp IWebBrowserInternal^ _webBrowserInternal; JavascriptObjectRepository^ _javaScriptObjectRepository; JavascriptCallbackFactory^ _javascriptCallbackFactory; - MethodRunnerQueue^ _methodRunnerQueue; + IMethodRunnerQueue^ _methodRunnerQueue; IBrowser^ _browserWrapper; bool _isDisposed; @@ -61,7 +61,16 @@ namespace CefSharp _webBrowserInternal = webBrowserInternal; _javaScriptObjectRepository = gcnew CefSharp::Internals::JavascriptObjectRepository(); _javascriptCallbackFactory = gcnew CefSharp::Internals::JavascriptCallbackFactory(_clientAdapter->GetPendingTaskRepository()); - _methodRunnerQueue = gcnew CefSharp::Internals::MethodRunnerQueue(_javaScriptObjectRepository); + + if (CefSharpSettings::ConcurrentTaskExecution) + { + _methodRunnerQueue = gcnew CefSharp::Internals::ConcurrentMethodRunnerQueue(_javaScriptObjectRepository); + } + else + { + _methodRunnerQueue = gcnew CefSharp::Internals::MethodRunnerQueue(_javaScriptObjectRepository); + } + _methodRunnerQueue->MethodInvocationComplete += gcnew EventHandler(this, &ManagedCefBrowserAdapter::MethodInvocationComplete); _methodRunnerQueue->Start(); } @@ -126,9 +135,9 @@ namespace CefSharp CefSharp::Internals::JavascriptObjectRepository^ get(); } - virtual property MethodRunnerQueue^ MethodRunnerQueue + virtual property IMethodRunnerQueue^ MethodRunnerQueue { - CefSharp::Internals::MethodRunnerQueue^ get(); + CefSharp::Internals::IMethodRunnerQueue^ get(); } }; } diff --git a/CefSharp.Example/CefExample.cs b/CefSharp.Example/CefExample.cs index 917849b6c..5ee6f4020 100644 --- a/CefSharp.Example/CefExample.cs +++ b/CefSharp.Example/CefExample.cs @@ -17,6 +17,7 @@ namespace CefSharp.Example public const string DefaultUrl = BaseUrl + "/home.html"; public const string BindingTestUrl = BaseUrl + "/BindingTest.html"; public const string BindingTestSingleUrl = BaseUrl + "/BindingTestSingle.html"; + public const string BindingTestsAsyncTaskUrl = BaseUrl + "/BindingTestsAsyncTask.html"; public const string LegacyBindingTestUrl = BaseUrl + "/LegacyBindingTest.html"; public const string PostMessageTestUrl = BaseUrl + "/PostMessageTest.html"; public const string PluginsTestUrl = BaseUrl + "/plugins.html"; @@ -188,7 +189,8 @@ namespace CefSharp.Example //This must be set before Cef.Initialized is called CefSharpSettings.FocusedNodeChangedEnabled = true; - //Experimental option where bound async methods are queued on TaskScheduler.Default. + //Async Javascript Binding - methods are queued on TaskScheduler.Default. + //Set this to true to when you have methods that return Task //CefSharpSettings.ConcurrentTaskExecution = true; //Legacy Binding Behaviour doesn't work for cross-site navigation (navigating to a different domain) diff --git a/CefSharp.Example/CefSharp.Example.csproj b/CefSharp.Example/CefSharp.Example.csproj index 32d204f23..a6603eec0 100644 --- a/CefSharp.Example/CefSharp.Example.csproj +++ b/CefSharp.Example/CefSharp.Example.csproj @@ -155,6 +155,7 @@ + diff --git a/CefSharp.Example/CefSharpSchemeHandlerFactory.cs b/CefSharp.Example/CefSharpSchemeHandlerFactory.cs index 6020f71f0..7338c9bc0 100644 --- a/CefSharp.Example/CefSharpSchemeHandlerFactory.cs +++ b/CefSharp.Example/CefSharpSchemeHandlerFactory.cs @@ -54,7 +54,8 @@ namespace CefSharp.Example { "/Recaptcha.html", Resources.Recaptcha }, { "/UnicodeExampleGreaterThan32kb.html", Resources.UnicodeExampleGreaterThan32kb }, { "/UnocodeExampleEqualTo32kb.html", Resources.UnocodeExampleEqualTo32kb }, - { "/JavascriptCallbackTest.html", Resources.JavascriptCallbackTest } + { "/JavascriptCallbackTest.html", Resources.JavascriptCallbackTest }, + { "/BindingTestsAsyncTask.html", Resources.BindingTestsAsyncTask } }; } diff --git a/CefSharp.Example/JavascriptBinding/AsyncBoundObject.cs b/CefSharp.Example/JavascriptBinding/AsyncBoundObject.cs index 3b635b1a3..4e1e80392 100644 --- a/CefSharp.Example/JavascriptBinding/AsyncBoundObject.cs +++ b/CefSharp.Example/JavascriptBinding/AsyncBoundObject.cs @@ -6,8 +6,11 @@ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; +using System.Linq; +using System.Net; using System.Text; using System.Threading; +using System.Threading.Tasks; namespace CefSharp.Example.JavascriptBinding { @@ -147,5 +150,47 @@ namespace CefSharp.Example.JavascriptBinding {"data", MethodReturnsDictionary2()} }; } + + //The Following Test methods can only be used when + //CefSharpSettings.ConcurrentTaskExecution = true; + //There is a seperate set of QUnit tests for these + + public Task ReturnTaskStringAsync() + { + return Task.FromResult(nameof(ReturnTaskStringAsync)); + } + + public async void VoidReturnAsync() + { + await Task.Delay(1000); + + Debug.WriteLine("Delayed 1 second."); + } + + public async Task AsyncWaitTwoSeconds(string str) + { + await Task.Delay(2000); + + return str; + } + + public async Task AsyncDownloadFileAndSplitOnNewLines(string url) + { + var webClient = new WebClient(); + var download = await webClient.DownloadStringTaskAsync(new Uri(url)); + + var lines = download.Split('\n').Where(x => !string.IsNullOrEmpty(x.Trim())).ToArray(); + + return lines; + } + + //We expect an exception here, so tell VS to ignore + [DebuggerHidden] + public async Task AsyncThrowException() + { + await Task.Delay(2000); + + throw new Exception("Expected Exception"); + } } } diff --git a/CefSharp.Example/Properties/Resources.Designer.cs b/CefSharp.Example/Properties/Resources.Designer.cs index 7821c0a0e..f42a9add0 100644 --- a/CefSharp.Example/Properties/Resources.Designer.cs +++ b/CefSharp.Example/Properties/Resources.Designer.cs @@ -309,19 +309,46 @@ namespace CefSharp.Example.Properties { /// /// Looks up a localized string similar to <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> ///<html> - /// <head> - /// <title>Binding Test</title> - /// <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.4.1.css"> - /// </head> - /// <body> - /// <div id="qunit"></div> - /// <div id="qunit-fixture"></div> - /// <script src="https://code.jquery.com/qunit/qunit-2.4.1.js"></script> + ///<head> + /// <title>Binding Test Async Task</title> + /// <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.4.1.css"> + ///</head> + ///<body> + /// <div> + /// These tests require CefSharpSettings.ConcurrentTaskExecution = true; + /// Which by default is set to false + /// </div> /// - /// <script type="text/javascript"> - /// (async () => - /// { - /// await CefSharp.BindObjectAsync("boundAsync [rest of string was truncated]";. + /// <div id="qunit"></div> + /// <div id="qunit-fixture"></div> + /// <script src="https://code.jquery.com/qunit/qunit-2.4.1.js"></script> + /// + /// [rest of string was truncated]";. + /// + public static string BindingTestsAsyncTask { + get { + return ResourceManager.GetString("BindingTestsAsyncTask", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> + ///<html> + ///<head> + /// <title>Binding Test</title> + /// <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.4.1.css"> + ///</head> + ///<body> + /// <div> + /// These tests require CefSharpSettings.ConcurrentTaskExecution = true; + /// Which by default is set to false + /// </div> + /// + /// <div id="qunit"></div> + /// <div id="qunit-fixture"></div> + /// <script src="https://code.jquery.com/qunit/qunit-2.4.1.js"></script> + /// + /// <script typ [rest of string was truncated]";. /// public static string BindingTestSingle { get { diff --git a/CefSharp.Example/Properties/Resources.resx b/CefSharp.Example/Properties/Resources.resx index ed8a390d4..e359d9d60 100644 --- a/CefSharp.Example/Properties/Resources.resx +++ b/CefSharp.Example/Properties/Resources.resx @@ -217,6 +217,9 @@ ..\Resources\JavascriptCallbackTest.html;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 + + ..\Resources\BindingTestsAsyncTask.html;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 + ..\Resources\PostMessageTest.html;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 diff --git a/CefSharp.Example/Resources/BindingTestSingle.html b/CefSharp.Example/Resources/BindingTestSingle.html index 3b1078877..749986310 100644 --- a/CefSharp.Example/Resources/BindingTestSingle.html +++ b/CefSharp.Example/Resources/BindingTestSingle.html @@ -1,52 +1,68 @@ - + - - Binding Test - - - -
-
- + + Binding Test + + + +
+ These tests require CefSharpSettings.ConcurrentTaskExecution = true; + Which by default is set to false +
- + + + - + diff --git a/CefSharp.Example/Resources/BindingTestsAsyncTask.html b/CefSharp.Example/Resources/BindingTestsAsyncTask.html new file mode 100644 index 000000000..7789db329 --- /dev/null +++ b/CefSharp.Example/Resources/BindingTestsAsyncTask.html @@ -0,0 +1,109 @@ + + + + Binding Test Async Task + + + +
+ These tests require CefSharpSettings.ConcurrentTaskExecution = true; + Which by default is set to false +
+ +
+
+ + + + + + diff --git a/CefSharp.Test/CefSharp.Test.csproj b/CefSharp.Test/CefSharp.Test.csproj index 39bcc7941..826f7df85 100644 --- a/CefSharp.Test/CefSharp.Test.csproj +++ b/CefSharp.Test/CefSharp.Test.csproj @@ -99,6 +99,7 @@ + @@ -113,6 +114,10 @@ CefSharp.Core True + + {a4394e7b-1155-43a6-989e-8ab72dddc9e4} + CefSharp.Example + {483b158d-f57d-49d9-9046-31e6a73f8a53} CefSharp.OffScreen diff --git a/CefSharp.Test/Framework/ConcurrentMethodRunnerQueueFacts.cs b/CefSharp.Test/Framework/ConcurrentMethodRunnerQueueFacts.cs new file mode 100644 index 000000000..9b81a0f89 --- /dev/null +++ b/CefSharp.Test/Framework/ConcurrentMethodRunnerQueueFacts.cs @@ -0,0 +1,77 @@ +// Copyright © 2019 The CefSharp Authors. All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. + +using System.Threading; +using System.Threading.Tasks; +using CefSharp.Example.JavascriptBinding; +using CefSharp.Internals; +using Xunit; +using Xunit.Abstractions; + +namespace CefSharp.Test.Framework +{ + public class ConcurrentMethodRunnerQueueFacts + { + private readonly ITestOutputHelper output; + + public ConcurrentMethodRunnerQueueFacts(ITestOutputHelper output) + { + this.output = output; + } + + [Fact] + public async Task StopConcurrentMethodRunnerQueueWhenMethodRunning() + { + var boundObject = new AsyncBoundObject(); + + var objectRepository = new JavascriptObjectRepository(); + objectRepository.Register("testObject", boundObject, true, new BindingOptions { CamelCaseJavascriptNames = false }); + var methodInvocation = new MethodInvocation(1, 1, 1, nameof(boundObject.AsyncWaitTwoSeconds), 1); + methodInvocation.Parameters.Add("Echo Me!"); + var methodRunnerQueue = new ConcurrentMethodRunnerQueue(objectRepository); + + methodRunnerQueue.Start(); + methodRunnerQueue.Enqueue(methodInvocation); + + //Wait a litle for the queue to start processing our Method call + await Task.Delay(500); + + var ex = Record.Exception(() => methodRunnerQueue.Stop()); + + Assert.Null(ex); + } + + [Fact] + public void ValidateAsyncTaskMethodOutput() + { + const string expectedResult = "Echo Me!"; + var boundObject = new AsyncBoundObject(); + + var objectRepository = new JavascriptObjectRepository(); + objectRepository.Register("testObject", boundObject, true, new BindingOptions { CamelCaseJavascriptNames = false }); + var methodInvocation = new MethodInvocation(1, 1, 1, nameof(boundObject.AsyncWaitTwoSeconds), 1); + methodInvocation.Parameters.Add(expectedResult); + var methodRunnerQueue = new ConcurrentMethodRunnerQueue(objectRepository); + var manualResetEvent = new ManualResetEvent(false); + + var actualResult = ""; + + methodRunnerQueue.MethodInvocationComplete += (sender, args) => + { + methodRunnerQueue.Stop(); + + actualResult = args.Result.Result.ToString(); + + manualResetEvent.Set(); + }; + + methodRunnerQueue.Start(); + methodRunnerQueue.Enqueue(methodInvocation); + + manualResetEvent.WaitOne(3000); + + Assert.Equal(expectedResult, actualResult); + } + } +} diff --git a/CefSharp.Wpf.Example/MainWindow.xaml b/CefSharp.Wpf.Example/MainWindow.xaml index e3d85ca24..b06fd9826 100644 --- a/CefSharp.Wpf.Example/MainWindow.xaml +++ b/CefSharp.Wpf.Example/MainWindow.xaml @@ -26,6 +26,7 @@ + @@ -43,6 +44,7 @@ + + + diff --git a/CefSharp/Internals/ConcurrentMethodRunnerQueue.cs b/CefSharp/Internals/ConcurrentMethodRunnerQueue.cs new file mode 100644 index 000000000..91b5b19fb --- /dev/null +++ b/CefSharp/Internals/ConcurrentMethodRunnerQueue.cs @@ -0,0 +1,191 @@ +// Copyright © 2019 The CefSharp Authors. All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. + +using System; +using System.Collections.Concurrent; +using System.Threading; +using System.Threading.Tasks; + +namespace CefSharp.Internals +{ + /// + /// ConcurrentMethodRunnerQueue - Async Javascript Binding methods are run + /// on the ThreadPool in parallel, when a method returns a Task + /// the we use ContinueWith to be notified of completion then + /// raise the MethodInvocationComplete event + /// + public class ConcurrentMethodRunnerQueue : IMethodRunnerQueue + { + private readonly JavascriptObjectRepository repository; + private readonly AutoResetEvent stopped = new AutoResetEvent(false); + private readonly BlockingCollection> queue = new BlockingCollection>(); + private readonly object lockObject = new object(); + private volatile CancellationTokenSource cancellationTokenSource; + private volatile bool running; + + public event EventHandler MethodInvocationComplete; + + public ConcurrentMethodRunnerQueue(JavascriptObjectRepository repository) + { + this.repository = repository; + } + + public void Start() + { + lock (lockObject) + { + if (!running) + { + cancellationTokenSource = new CancellationTokenSource(); + Task.Factory.StartNew(ConsumeTasks, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + running = true; + } + } + } + + public void Stop() + { + lock (lockObject) + { + if (running) + { + cancellationTokenSource.Cancel(); + stopped.WaitOne(); + //clear the queue + while (queue.Count > 0) + { + queue.Take(); + } + cancellationTokenSource = null; + running = false; + } + } + } + + public void Enqueue(MethodInvocation methodInvocation) + { + queue.Add(() => ExecuteMethodInvocation(methodInvocation)); + } + + private void ConsumeTasks() + { + try + { + //Executes tasks on the ThreadPool + while (!cancellationTokenSource.IsCancellationRequested) + { + var func = queue.Take(cancellationTokenSource.Token); + + var task = new Task(() => + { + var result = func(); + + //If the call failed or returned null then we'll fire the event immediately + if (!result.Success || result.Result == null) + { + OnMethodInvocationComplete(result); + } + else + { + var resultType = result.Result.GetType(); + + //If the returned type is Task then we'll ContinueWith and perform the processing then. + if (typeof(Task).IsAssignableFrom(resultType)) + { + var resultTask = (Task)result.Result; + + if (resultType.IsGenericType) + { + resultTask.ContinueWith((t) => + { + if (t.Status == TaskStatus.RanToCompletion) + { + //We use some reflection to get the Result + //If someone has a better way of doing this then please submit a PR + result.Result = resultType.GetProperty("Result").GetValue(resultTask); + } + else + { + result.Success = false; + result.Result = null; + var aggregateException = t.Exception; + //TODO: Add support for passing a more complex message + // to better represent the Exception + if (aggregateException.InnerExceptions.Count == 1) + { + result.Message = aggregateException.InnerExceptions[0].ToString(); + } + else + { + result.Message = t.Exception.ToString(); + } + } + + OnMethodInvocationComplete(result); + }, + cancellationTokenSource.Token, TaskContinuationOptions.None, TaskScheduler.Default); + } + else + { + //If it's not a generic Task then it doesn't have a return object + //So we'll just set the result to null and continue on + result.Result = null; + + OnMethodInvocationComplete(result); + } + } + else + { + OnMethodInvocationComplete(result); + } + } + + }, cancellationTokenSource.Token); + + task.Start(TaskScheduler.Default); + } + } + catch (OperationCanceledException) + { + // Note: Task has been cancelled + } + finally + { + stopped.Set(); + } + } + + private MethodInvocationResult ExecuteMethodInvocation(MethodInvocation methodInvocation) + { + object result = null; + string exception; + var success = false; + + //make sure we don't throw exceptions in the executor task + try + { + success = repository.TryCallMethod(methodInvocation.ObjectId, methodInvocation.MethodName, methodInvocation.Parameters.ToArray(), out result, out exception); + } + catch (Exception e) + { + exception = e.Message; + } + + return new MethodInvocationResult + { + BrowserId = methodInvocation.BrowserId, + CallbackId = methodInvocation.CallbackId, + FrameId = methodInvocation.FrameId, + Message = exception, + Result = result, + Success = success + }; + } + + private void OnMethodInvocationComplete(MethodInvocationResult e) + { + MethodInvocationComplete?.Invoke(this, new MethodInvocationCompleteArgs(e)); + } + } +} diff --git a/CefSharp/Internals/IBrowserAdapter.cs b/CefSharp/Internals/IBrowserAdapter.cs index dea40cdad..0d09ea92c 100644 --- a/CefSharp/Internals/IBrowserAdapter.cs +++ b/CefSharp/Internals/IBrowserAdapter.cs @@ -10,7 +10,7 @@ namespace CefSharp.Internals /// public interface IBrowserAdapter { - MethodRunnerQueue MethodRunnerQueue { get; } + IMethodRunnerQueue MethodRunnerQueue { get; } JavascriptObjectRepository JavascriptObjectRepository { get; } IJavascriptCallbackFactory JavascriptCallbackFactory { get; } void OnAfterBrowserCreated(IBrowser browser); diff --git a/CefSharp/Internals/IMethodRunnerQueue.cs b/CefSharp/Internals/IMethodRunnerQueue.cs new file mode 100644 index 000000000..7c04b5fff --- /dev/null +++ b/CefSharp/Internals/IMethodRunnerQueue.cs @@ -0,0 +1,17 @@ +// Copyright © 2019 The CefSharp Authors. All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. + +using System; + +namespace CefSharp.Internals +{ + public interface IMethodRunnerQueue + { + event EventHandler MethodInvocationComplete; + + void Enqueue(MethodInvocation methodInvocation); + void Start(); + void Stop(); + } +} diff --git a/CefSharp/Internals/MethodRunnerQueue.cs b/CefSharp/Internals/MethodRunnerQueue.cs index 9c518cfc9..463188340 100644 --- a/CefSharp/Internals/MethodRunnerQueue.cs +++ b/CefSharp/Internals/MethodRunnerQueue.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; namespace CefSharp.Internals { - public sealed class MethodRunnerQueue + public sealed class MethodRunnerQueue : IMethodRunnerQueue { private readonly JavascriptObjectRepository repository; private readonly AutoResetEvent stopped = new AutoResetEvent(false); @@ -67,29 +67,12 @@ namespace CefSharp.Internals { try { - - if (CefSharpSettings.ConcurrentTaskExecution) + //Tasks are run in sequential order on the current Thread. + while (!cancellationTokenSource.IsCancellationRequested) { - //New experimental behaviour that Starts the Tasks on TaskScheduler.Default - while (!cancellationTokenSource.IsCancellationRequested) - { - var task = queue.Take(cancellationTokenSource.Token); - task.ContinueWith((t) => - { - OnMethodInvocationComplete(t.Result); - }, cancellationTokenSource.Token); - task.Start(TaskScheduler.Default); - } - } - else - { - //Old behaviour, runs Tasks in sequential order on the current Thread. - while (!cancellationTokenSource.IsCancellationRequested) - { - var task = queue.Take(cancellationTokenSource.Token); - task.RunSynchronously(); - OnMethodInvocationComplete(task.Result); - } + var task = queue.Take(cancellationTokenSource.Token); + task.RunSynchronously(); + OnMethodInvocationComplete(task.Result); } } catch (OperationCanceledException) @@ -112,6 +95,23 @@ namespace CefSharp.Internals try { success = repository.TryCallMethod(methodInvocation.ObjectId, methodInvocation.MethodName, methodInvocation.Parameters.ToArray(), out result, out exception); + + //We don't support Tasks by default + if (success && result != null && (typeof(Task).IsAssignableFrom(result.GetType()))) + { + //Use StringBuilder to improve the formatting/readability of the error message + //I'm sure there's a better way I just cannot remember of the top of my head so going + //with this for now, as it's only for error scenaiors I'm not concerned about performance. + var builder = new System.Text.StringBuilder(); + builder.AppendLine("Your method returned a Task which is not supported by default you must set CefSharpSettings.ConcurrentTaskExecution = true; before creating your first ChromiumWebBrowser instance."); + builder.AppendLine("This will likely change to the default at some point in the near future, subscribe to the issue link below to be notified of any changes."); + builder.AppendLine("See https://github.com/cefsharp/CefSharp/issues/2758 for more details, please report any issues you have there, make sure you have an example ready that reproduces your problem."); + + success = false; + result = null; + exception = builder.ToString(); + } + } catch (Exception e) {