I'm using Roslyn's scripting API in my application, code snippet as following:
public class ScriptEngine
{
public static string CodeText;
public static event Action<string[]> CompileErrorEvent;
public static async Task<bool> RunScriptAsync(CancellationToken ct)
{
try
{
var scriptResult = await CSharpScript.RunAsync(CodeText, null, new ScriptHost(), null, ct);
return true;
}
catch (Microsoft.CodeAnalysis.Scripting.CompilationErrorException ex)
{
List<string> result = new List<string>();
foreach (var item in ex.Diagnostics)
{
result.Add(item.ToString());
}
if (result.Count > 0)
{
CompileErrorEvent?.Invoke(result.ToArray());
}
return false;
}
catch (Exception ex)
{
IMCP_Base.Dialog.Show.SimpleError("脚本运行", ex.Message, "修改脚本");
return false;
}
}
.......
}
public static CancellationTokenSource ScriptCTS;
private async void btnScriptRun_ItemClick(object sender, ItemClickEventArgs e)
{
ScriptCTS = new CancellationTokenSource();
if (CheckScriptEditorIsNotNull())
{
Script.ScriptEngine.CodeText = ScriptEditor.GetCode();
bool runSuccess = await Script.ScriptEngine.RunScriptAsync(ScriptCTS.Token);
}
}
private void btnScriptStop_ItemClick(object sender, ItemClickEventArgs e)
{
ScriptCTS?.Cancel();
}
CSharpScript.RunAsync method runs well, but when I click ScriptStop button, ScriptCTS?.Cancel() can't cancel running script.
How can I stop or pause a script running?
If you want cancellation points within your scripts, you can use globals, and pass in the CancelationToken, which you can then check in your scripts for cancellation.
Related
I am generating more than 100 messages per second and sending these messages in separate thread. When connection is down, I want to catch the exception in caller. Since all my messages are sent asynchronous, I am not able to catch the exceptions.
Here is the DispatcherTimer code which calls the dispatcherTimer_Tick method
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
try
{
item = "some generated message";
Task.Run(() => SendMessage(item));
}
catch (Exception)
{
}
}
Here is the SendMessage code. I have made change by reading Based on: Async/Await - Best Practices in Asynchronous Programming, BUT it's not working
private async static Task SendMessage(string message)
{
try
{
(MQTT.RunAsync(message.ToString(), topic)).Wait();
}
catch (Exception Ex)
{
// Exceptions are not getting cought here
}
}
Definition of MQTT.RunAsync
public static async Task RunAsync(string message)
{
var mqttClient = factory.CreateMqttClient()
try
{
await mqttClient.ConnectAsync(options);
}
catch (Exception exception)
{
}
}
And
Task<MqttClientConnectResult> ConnectAsync(IMqttClientOptions options)
Updated Question
My RunAsync is first trying to connect and if success then it sends the message. so I can't write return while connection check.
public Task RunAsync(string message, string topicName)
{
this.mqttClient.ConnectAsync(this.options);
mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(this._topicname).WithExactlyOnceQoS().Build());
var applicationMessage = new MqttApplicationMessageBuilder().WithTopic(this._topicname)
.WithPayload(message).WithAtLeastOnceQoS().Build();
if (stopSending == false)
{
return mqttClient.PublishAsync(applicationMessage);
}
return null;
}
Event handlers are an exception where async void is allowed
private async void dispatcherTimer_Tick(object sender, EventArgs e) {
try {
item = "some generated message";
await SendMessage(item);
} catch (Exception ex) {
//...handle exception
}
}
Plus you appear to be consuming the exception any way as it is already being caught further down the stack.
Try to keep the code async all the way through and not mix blocking calls like .Wait() or .Result
private static Task SendMessage(string message) {
return MQTT.RunAsync(message, topic);
}
public static async Task RunAsync(string message, string topicName) {
await this.mqttClient.ConnectAsync(this.options);
var topicFilter = new TopicFilterBuilder().WithTopic(this._topicname)
.WithExactlyOnceQoS().Build();
await mqttClient.SubscribeAsync(topicFilter);
var applicationMessage = new MqttApplicationMessageBuilder().WithTopic(this._topicname)
.WithPayload(message).WithAtLeastOnceQoS().Build();
if (stopSending == false) {
await mqttClient.PublishAsync(applicationMessage);
}
}
i have one form which is doing some long process on form load event,
So i want to show One Gif image "Please Wait" during form load event.
below is code.
private void frmWaitShow()
{
try
{
frmWaitwithstatus objWait = new frmWaitwithstatus();// this form has Gif Image for Processing
objWait.lblStatus.Text = "Processing Request, Please wait...";
objWait.ShowDialog();
}
catch (Exception ex)
{
Logger.SystemException(ex);
Logger.FTSError(" ERROR :" + ex.Message + "frmTest || frmWaitShow");
}
}
Thread oThread;
private void frmTest_Load(object sender, EventArgs e)
{
try
{
oThread = new Thread(new ThreadStart(frmWaitShow));
oThread.Start();
//Functions for Connection with devices
if (LoadDatafromDB() == false) return;
if (ElectTestLoad() == false) return;
if (PowerOnSelfTest() == false) { return; }
InitiControlsElectTest();
SetSystemMode(SystemMode.ElectricalMode);
oThread.Abort();
}
catch (Exception ex)
{
oThread.Abort();
Logger.SystemException(ex);
}
}
after Thread.start() my debugger go one one step in each thread main and one i created but after it go to below line.
frmWaitwithstatus.cs constructor first line
public frmWaitwithstatus()
it stop execute my Thread and execute all function of main thread once Main Thread execution complete after then only it start execute my thread (which is Gif processing image).
Using the async/await pattern will made this an easy task and every form will work on UI thread:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void Form1_Load(object sender, EventArgs e)
{
// async show loading form dialog
var loadingForm = new LoadingForm();
var loadingDialogTask = this.InvokeAsync(loadingForm.ShowDialog);
// async loading data
var data = await LoadDataAsync();
listBox1.DataSource = data;
loadingForm.Close();
await loadingDialogTask;
}
private async Task<ICollection<string>> LoadDataAsync()
{
// fake work load
await Task.Delay(4000).ConfigureAwait(false);
return Enumerable.Range(1,20000).Select(e => e.ToString()).ToList();
}
}
Needed async extension for the controls:
public static class ControlAsyncExtensions
{
public static Task InvokeAsync(this Control control, Action action)
{
var tcs = new TaskCompletionSource<bool>();
control.BeginInvoke(new Action(() =>
{
try
{
action();
tcs.SetResult(true);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
}
));
return tcs.Task;
}
public static Task<T> InvokeAsync<T>(this Control control, Func<T> action)
{
var tcs = new TaskCompletionSource<T>();
control.BeginInvoke(new Action(() =>
{
try
{
tcs.SetResult(action());
}
catch (Exception ex)
{
tcs.SetException(ex);
}
}
));
return tcs.Task;
}
}
I have a project that without usign any form/button or nothing like that, connects with a Websocket and using async methods receives some message(on a form created by myself) that is supposed to appear on the top-right corner of the screen.
But this message can appear from time to time (2 or 3 minutes) on the screen if the websocket doesn't say that it must stop. And this message can be big enough, that in order to make it look better I make my message appear in more than one form.
It causes an impression that it's a notification. So my class that connects with the websocket and receives the message async, calls another class using a thread that is a controller. The purpose of the controller is from time to time, show that message in various new form() notifications and obviously don't do it if the websocket doesn't return any message.
But when i call the form.show the program stops working.
I've looked around stackoverflow already, but the ideas that i've found didn't seem to work.
Some say that I should use invoke, but it kept giving error saying that
"Invoke or BeginInvoke cannot be called on a control until the window handle has been created", tried to solve like this: C# calling form.show() from another thread but it didn't work.
Some said that I should use .showDialog instead of .show, but it doesn't appear to be good, because it waits the window to be closed to terminate the method and as I said I need to open more than one notification at the same time.
Some said that the form was open with .show, but it was open for a very little period of time. But i couldn't notice if that was the case and even if it was i couldn't solve it. Well, what matter is that i'm stuck and i don't know what to do more.
Edited with Code:
//Main
Application.Run(new SocketService());
//SocketService class
public SocketService()
{
alerta = null;
while (true)
{
try
{
//Console.WriteLine("Nome do Usúario:" + Environment.UserName);
Thread.Sleep(2000);
Connect("ws://192.168.120.38:9091").Wait();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
public static async Task Connect(string uri)
{
ClientWebSocket webSocket = null;
try
{
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
await Login(webSocket);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (webSocket != null)
webSocket.Dispose();
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebSocket closed.");
Console.ResetColor();
}
}
}
private static async Task Login(ClientWebSocket webSocket)
{
ArraySegment<Byte> buffer = new ArraySegment<byte>(encoder.GetBytes( "{\"event\":\"loginBrowser\",\"data\":{\"login\":\"000000003077\",\"data\":\"1\"}}"));
await webSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
if (webSocket.State == WebSocketState.Open)
{
if (ShowMessage.created != true)
{
var dummy = new Control(); // to initialize SynchronizationContext
_sync = SynchronizationContext.Current;
new Thread(ThreadProc).Start();
}
await Receive(webSocket);
}
}
private static async Task Receive(ClientWebSocket webSocket)
{
while (webSocket.State == WebSocketState.Open)
{
ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[256]);
var result = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
else
{
if (result.EndOfMessage)
{
message += encoder.GetString(buffer.ToArray());
SendMessage(message);
}
else
{
message += encoder.GetString(buffer.ToArray());
}
}
}
}
public static void ShowFormFromAnotherThread(string text)
{
_sync.Post(SendOrPostCallback, text);
}
private static void SendOrPostCallback(object state)
{
var form = new Notification();
form.Text = (string)state;
form.Show();
}
private static void ThreadProc()
{
while (true)
{
Thread.Sleep(2000); // wait imitation
ShowFormFromAnotherThread("HI");
}
}
/*Notification is my form and depending on where I put this part:
var dummy = new Control(); // to initialize SynchronizationContext
_sync = SynchronizationContext.Current;
new Thread(ThreadProc).Start();
Or i doesn't call login or doesn't enter receive() method or the best case It receives the information
calls the threadProc and the ShowFormFromAnotherThread but doesn't enter SednOrPostCallBack*/
using System.Threading;
using System.Windows.Forms;
namespace ConsoleThreadSync
{
internal class Program
{
private static void Main(string[] args)
{
Application.Run(new App());
}
}
public class App : ApplicationContext
{
private readonly SynchronizationContext _sync;
public App()
{
var dummy = new Control(); // to initialize SynchronizationContext
_sync = SynchronizationContext.Current;
new Thread(ThreadProc).Start();
}
public void ShowFormFromAnotherThread(string text)
{
_sync.Post(SendOrPostCallback, text);
}
private void SendOrPostCallback(object state)
{
var form = new Form1();
form.Text = (string)state;
form.Show();
}
private void ThreadProc()
{
while (true)
{
Thread.Sleep(2000); // wait imitation
ShowFormFromAnotherThread("HI");
}
}
}
}
Try to call this:
var dummy = new Control(); // to initialize SynchronizationContext
_sync = SynchronizationContext.Current;
from a contructor SocketService() and not from async methods. This is an initialization code and it must call from main thread.
Okay, after reading a little bit more, the solution that kind worked out was this one, but the only way of using the
.show from the notifician is to use the Application.DoEvents and I've been warned from the sources that I've looked into
that this method should not be used, unless is the only option, because It can cause some problems with the Threads and other things.
So unless someone can give me another hint or clue about what to do, I have two options or use this method and try to fix some other bug
that It can cause or use the .showDialog because don't know why It works without any other problem, but to use .showDialog I've
to use another thread where I create and show the notification because if I don't do, the loop will stop at each iteration
in order to wait the .showDialog be closed. And as it isn't a problem I want to avoid using a lot of threads, because it can cause
another problem with the sync between them:
namespace ReiDoCSharp
{
class ShowMessage
{
private static RootObject alerta;
public static bool created;
private static int startPosition;
public static void setStartPosition(int start)
{
if (start < startPosition)
{
startPosition = start;
}
}
public RootObject getAlerta()
{
return ShowMessage.alerta;
}
public void setAlerta(RootObject root)
{
ShowMessage.alerta = root;
}
private static void DoWork()
{
while (true)
{
if (created != true)
{
created = true;
}
if (alerta != null)
{
string mensagem = "";
if ((alerta.data.Informacoes[1] != "") && (alerta.data.Informacoes[1] != null))
{
mensagem += alerta.data.Informacoes[1];
}
if ((alerta.data.Informacoes[0] != "") && (alerta.data.Informacoes[0] != null))
{
mensagem += alerta.data.Informacoes[0];
}
if (mensagem != "")
{
startPosition = 5;
string[] messages = mensagem.Split(new[] { "<br><br>" }, StringSplitOptions.None);
foreach (string message in messages)
{
Notification popup = new Notification();
popup.label1.Text = message;
popup.TopMost = true;
popup.Show();
Application.DoEvents();
/*Solution with the ShowDialog would be:
Task.Run(() => showNotification(message));
*/
}
}
}
Thread.Sleep(5000);
}
}
//Then I won't need to use Application.DoEvents, but would have to create more threads
private static Task showNotification(string message)
{
Notification popup = new Notification();
popup.label1.Text = message;
popup.TopMost = true;
popup.ShowDialog();
}
public static Task createPopupsAsync()
{
Task.Run(() => DoWork());
}
}
}
namespace ReiDoCSharp
{
class SocketService
{
private static object consoleLock = new object();
private const bool verbose = true;
private static readonly TimeSpan delay = TimeSpan.FromMilliseconds(3000);
private static UTF8Encoding encoder = new UTF8Encoding();
private static string message;
private static RootObject alerta;
public SocketService()
{
Begin();
}
public static void Begin()
{
alerta = null;
while (true)
{
try
{
Thread.Sleep(2000);
Connect("ws://192.168.120.38:9091").Wait();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
public static async Task Connect(string uri)
{
ClientWebSocket webSocket = null;
try
{
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
await Login(webSocket);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (webSocket != null)
webSocket.Dispose();
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebSocket closed.");
Console.ResetColor();
}
}
}
private static async Task Login(ClientWebSocket webSocket)
{
ArraySegment<Byte> buffer = new ArraySegment<byte>(encoder.GetBytes("{\"event\":\"loginBrowser\",\"data\":{\"OPERADOR\":\"000000003077\",\"NRORG\":\"1\"}}"));
await webSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
if (webSocket.State == WebSocketState.Open)
{
Task.Factory.StartNew(() => ShowMessage.createPopupsAsync());
await Receive(webSocket);
}
}
private static async Task Receive(ClientWebSocket webSocket)
{
while (webSocket.State == WebSocketState.Open)
{
ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[256]);
var result = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
else
{
if (result.EndOfMessage)
{
message += encoder.GetString(buffer.ToArray());
SendMessage(message);
}
else
{
message += encoder.GetString(buffer.ToArray());
}
}
}
}
private static void LogStatus(bool receiving, byte[] buffer, int length, string assunto)
{
lock (consoleLock)
{
Console.ForegroundColor = receiving ? ConsoleColor.Green : ConsoleColor.Yellow;
if (verbose)
{
Console.WriteLine(encoder.GetString(buffer) + " " + assunto);
}
Console.ResetColor();
}
}
private static void SendMessage(string message)
{
message = message.Replace("event", "evento");
message = message.Replace("\0", "");
JavaScriptSerializer js = new JavaScriptSerializer();
RootObject mess = js.Deserialize<RootObject>(message);
if (mess.data.Informacoes[1] != "")
{
mess.data.Informacoes[1] += "<br>";
}
if (alerta == null)
{
alerta = mess;
}
else
{
if ((mess.data.Quantidade[0] != 0) && (mess.data.Quantidade == null))
{
if ((mess.data.Quantidade[0] == -1) && (mess.data.Informacoes[0] == ""))
{
alerta = null;
}
else
{
alerta = mess;
}
}
else if (mess.data.Quantidade[0] == 0)
{
alerta = null;
}
if ((mess.data.Quantidade[1] != 0) && (mess.data.Informacoes[1] != ""))
{
alerta = mess;
}
}
new ShowMessage().setAlerta(alerta);
message = "";
}
}
}
I am trying to get my form to wait until a particular part of my _Load method is finished before continuing. I have a few methods that are async, but I cannot figure out why I am not able to get the code to wait until fakeClickCheckUpdate is finished before continuing. Here are the main methods involved:
public myForm(string args)
{
InitializeComponent();
Load += myForm_Load;
}
private void myForm_Load(object s, EventArgs e)
{
this.fakeClickCheckUpdate();
loadFinished = true;
if (this.needsUpdate == true)
{
Console.WriteLine("Needs update...");
}
else
{
Console.WriteLine("update is false");
}
}
public void fakeClickCheckUpdate()
{
this.checkUpdateButton.PerformClick();
}
private async void checkUpdateButton_Click(object sender, EventArgs e)
{
await startDownload(versionLink, versionSaveTo);
await checkVersion();
Console.WriteLine(needsUpdate);
}
private async Task checkVersion()
{
string currVersion;
string newVersion;
using (StreamReader sr = new StreamReader(currVersionTxt))
{
currVersion = sr.ReadToEnd();
}
using (StreamReader nr = new StreamReader(versionSaveTo))
{
newVersion = nr.ReadToEnd();
}
if (!newVersion.Equals(currVersion, StringComparison.InvariantCultureIgnoreCase))
{
this.BeginInvoke((MethodInvoker)delegate
{
progressLabel.Text = "New version available! Please select 'Force Download'";
});
this.needsUpdate = true;
}
else
{
this.BeginInvoke((MethodInvoker)delegate
{
progressLabel.Text = "Your version is up-to-date. No need to update.";
});
this.needsUpdate = false;
}
}
Basically, I want it to check the current version with checkVersion and finish that before it tries to continue past loadFinished = true inside of myForm_Load. I have checkVersion set as an async Task so that the button click can use await on it. Is there any way to get the functionality I need with this code?
First, move your code out of your perform click action.
private async void checkUpdateButton_Click(object sender, EventArgs e)
{
await CheckForUpdate();
}
private async Task CheckForUpdate()
{
await startDownload(versionLink, versionSaveTo);
await checkVersion();
Console.WriteLine(needsUpdate);
}
You can then call that same function in your OnLoad.
private async void myForm_Load(object s, EventArgs e)
{
await CheckForUpdate();
loadFinished = true;
if (this.needsUpdate == true)
{
Console.WriteLine("Needs update...");
}
else
{
Console.WriteLine("update is false");
}
}
This question already has answers here:
A pattern to pause/resume an async task?
(5 answers)
Closed 5 years ago.
I have a sample code, taken from MSDN, to which I would like implement the Pause / Resume functionality within while loop. Could anybody propose a solution / parern which would hande this?
private async void startButton_Click(object sender, RoutedEventArgs e)
{
resultsTextBox.Clear();
// Instantiate the CancellationTokenSource.
cts = new CancellationTokenSource();
try
{
await AccessTheWebAsync(cts.Token);
resultsTextBox.Text += "\r\nDownloads complete.";
}
catch (OperationCanceledException)
{
resultsTextBox.Text += "\r\nDownloads canceled.\r\n";
}
catch (Exception)
{
resultsTextBox.Text += "\r\nDownloads failed.\r\n";
}
cts = null;
}
private void cancelButton_Click(object sender, RoutedEventArgs e)
{
if (cts != null)
{
cts.Cancel();
}
}
async Task AccessTheWebAsync(CancellationToken ct)
{
HttpClient client = new HttpClient();
// Make a list of web addresses.
List<string> urlList = SetUpURLList();
// ***Create a query that, when executed, returns a collection of tasks.
IEnumerable<Task<int>> downloadTasksQuery =
from url in urlList select ProcessURL(url, client, ct);
// ***Use ToList to execute the query and start the tasks.
List<Task<int>> downloadTasks = downloadTasksQuery.ToList();
// ***Add a loop to process the tasks one at a time until none remain.
while (downloadTasks.Count > 0)
{
// Identify the first task that completes.
Task<int> firstFinishedTask = await Task.WhenAny(downloadTasks);
// ***Remove the selected task from the list so that you don't
// process it more than once.
downloadTasks.Remove(firstFinishedTask);
// Await the completed task.
int length = await firstFinishedTask;
resultsTextBox.Text += String.Format("\r\nLength of the download: {0}", length);
}
}
There is an MSDN article that solves this using a PauseToken (similar to a CancellationToken).
Here's the sample code from that article that demonstrates this concept:
namespace PauseTokenTestApp
{
public class PauseTokenSource
{
private volatile TaskCompletionSource<bool> m_paused;
internal static readonly Task s_completedTask = Task.FromResult(true);
public bool IsPaused
{
get { return m_paused != null; }
set
{
if (value)
{
Interlocked.CompareExchange(
ref m_paused, new TaskCompletionSource<bool>(), null);
}
else
{
while (true)
{
var tcs = m_paused;
if (tcs == null) return;
if (Interlocked.CompareExchange(ref m_paused, null, tcs) == tcs)
{
tcs.SetResult(true);
break;
}
}
}
}
}
public PauseToken Token { get { return new PauseToken(this); } }
internal Task WaitWhilePausedAsync()
{
var cur = m_paused;
return cur != null ? cur.Task : s_completedTask;
}
}
public struct PauseToken
{
private readonly PauseTokenSource m_source;
internal PauseToken(PauseTokenSource source) { m_source = source; }
public bool IsPaused { get { return m_source != null && m_source.IsPaused; } }
public Task WaitWhilePausedAsync()
{
return IsPaused ?
m_source.WaitWhilePausedAsync() :
PauseTokenSource.s_completedTask;
}
}
class Program
{
static void Main()
{
var pts = new PauseTokenSource();
Task.Run(() =>
{
while (true)
{
Console.ReadLine();
pts.IsPaused = !pts.IsPaused;
}
});
SomeMethodAsync(pts.Token).Wait();
}
public static async Task SomeMethodAsync(PauseToken pause)
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(i);
await Task.Delay(100);
await pause.WaitWhilePausedAsync();
}
}
}
}