I made a WCF service which makes a callback to a WPF client. I just show the progress in a textbox in the WPF client. What I got first is cross thread operation not valid. Then I modified the client side code and implemented using methods such as Invoke() and BeginInvoke(). Now the client side code shows only the value 100%. Actually it should display the values from 0-100%. Any solutions?
The code at wcf service:
namespace ReportService
{
[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Reentrant,InstanceContextMode=InstanceContextMode.Single)]
public class Report : IReportService
{
public void ProcessReport()
{
for (int i = 1; i <= 100; i++)
{
Thread.Sleep(1000);
OperationContext.Current.GetCallbackChannel<IReportCallback>().ReportProgress(i);
}
}
}
}
Code at client:
namespace Report
{
[CallbackBehavior(UseSynchronizationContext=false)]
public partial class Form1 : Form,ReportService.IReportServiceCallback
{
delegate void delSetTxt(int percentCompleted);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
InstanceContext ic= new InstanceContext(this);
ReportService.ReportServiceClient client = new ReportService.ReportServiceClient(ic);
client.ProcessReport();
}
public void ReportProgress(int percentCompleted)
{
// this.Invoke(new Action(() => { this.textBox1.Text = percentCompleted.ToString(); }));
Thread t = new Thread(() => setTxt(percentCompleted));
t.Start();
}
public void setTxt(int percentCompleted)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new delSetTxt(setTxt), new object[] { percentCompleted });
return;
}
this.textBox1.Text = percentCompleted.ToString() + " % complete";
}
}
}
When the call is made to the service, the GUI thread is stuck in the button_click method.
So the GUI thread must not be frozen.
There are (at least) two solutions that work, I tested them :
Put [OperationContract(IsOneWay = true)] both on the server and the callback operation
Put [OperationContract(IsOneWay = true)] on the callback operation and don't lock GUI thread with await/async:
private async void button1_Click(object sender, EventArgs e)
{
InstanceContext ic = new InstanceContext(this);
ReportServiceClient client = new ReportServiceClient(ic);
await client.ProcessReportAsync();
//client.ProcessReport();
}
Good luck
Related
For the past 2 days I'm stuck on something but without solution.
I have a class which I wrote and one of its object is "SerialPort" .NET class.
In my MainWindow I created instance of my class called "SerialPortComm", then I send through some functions of mine, commands to the Serial Port, and I receive answers through "DataReceived" event.
But when I trying to use Dispatcher.BeginInvoke to write my data I have received (successfully), nothing shows on the RichTextBox which I'm trying to write to.
What can caused that, and How I can make it works?
SerialPortComm.cs (EDIT)
public partial class SerialPortComm : UserControl
{
public SerialPort mySerialPort = new SerialPort();
public void Open_Port(string comNumber, int baudRate)
{
mySerialPort.PortName = comNumber;
mySerialPort.BaudRate = baudRate;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
mySerialPort.Open();
}
public void SetStringDataFromControl(SerialPort sp, string content)
{
sp.Write(content + "\n");
}
public void SetStringDataFromControl(SerialPort sp, string content)
{
sp.Write(content + "\n");
}
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
DataRX = sp.ReadExisting(); // Read the data from the Serial Port
// Print it on the Log
RichTextBox_logView.Dispatcher.BeginInvoke((Action)delegate()
{
RichTextBox_logView.AppendText(DataRX);
RichTextBox_logView.ScrollToEnd();
});
}
}
Commands.cs
class Commands
{
public void SetCommand(SerialPortComm sp, string command)
{
sp.SetStringDataFromControl(sp.mySerialPort, command);
}
}
MainWindow.cs
public partial class MainWindow : Window
{
Commands cmd = new Commands();
SerialPortComm sp1 = new SerialPortComm();
public MainWindow()
{
InitializeComponent();
sp1.Open_Port("COM6", 115200);
}
private async void TextBox_input_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
cmd.SetCommand(sp1, "top");
cmd.SetCommand(sp1, "run");
// .... //
}
}
}
I think you have the UI thread blocked, try just invoking the COM message via a ThreadPool thread:
public void SetCommand(SerialPortComm sp, string command)
{
Task.Factory.StartNew( () => {
sp.SetStringDataFromControl(sp.mySerialPort, command);
});
}
The only issue with this is that these calls are not guaranteed to run and complete in sequence. You may have to tweak so that the calls are enqueued and consumed in order. See producer/consumer pattern via the Concurrent collections namespace.
http://www.nullskull.com/a/1464/producerconsumer-queue-and-blockingcollection-in-c-40.aspx
Alternatively you could avoid the concurrency issues by just invoking all the commands in their own dedicated (single) thread like this:
if (e.Key == Key.Enter)
{
Task.Factory.StartNew( () => {
cmd.SetCommand(sp1, "top");
cmd.SetCommand(sp1, "run");
// .... //
});
}
This is probably an easier implementation.
i am having trouble creating a callback on a newly started thread.
I have 2 classes, an API, and the Form.cs. I start a thread running a method in API, from Form.cs, i want to notify a method in Form.cs from inside the method in API.
I am familiar with delegation in Obj-C, but not in C#.
I only included the relevant code.
public partial class Main: Form
{
private Api Connect = new Api();
private void StartStopButton_Click(object sender, EventArgs e)
{
//new thread
Thread ThreadConnect = new Thread(Connect.startAttemptingWithUsername);
ThreadConnect.Start();
}
public void AttemptingWithPasswordMessage(string password)
{
// i want to notify this method from the API
}
}
class Api : UserAgent
{
public void startAttemptingWithUsername()
{
_shouldStop = false;
while (!_shouldStop)
{
Console.WriteLine(username);
// How would i notify AttemptingWithPasswordMessage from here?
System.Threading.Thread.Sleep(1000);
}
}
}
Provide an event to your other class, and fire that event whenever it is relevant based on the processing:
class Api : UserAgent
{
public event Action<string> SomeEvent;//TODO give better name
public void startAttemptingWithUsername()
{
_shouldStop = false;
while (!_shouldStop)
{
Console.WriteLine(username);
var handler = SomeEvent;
if (handler != null)
handler("asdf");
// How would i notify AttemptingWithPasswordMessage from here?
System.Threading.Thread.Sleep(1000);
}
}
}
Then add a handler for that event: (And marshal back to the UI thread)
private void StartStopButton_Click(object sender, EventArgs e)
{
//new thread
Thread ThreadConnect = new Thread(Connect.startAttemptingWithUsername);
ThreadConnect.Start();
Connect.SomeEvent += (data) => Invoke(
new Action(()=>AttemptingWithPasswordMessage(data)));
}
I have a FTP proccess that run without UI. and have a winform that use this ftp control. in that window I have a progressbar that show the ftp upload progress. The progress arrives to the window via interfase that is updated on the underliying presenter (I'm using MVP pattern).
My problem is when try to update the progress, it allways throw me this exception.
Through threads illegal operation: control 'prgProgresoSubido' is accessed from a thread other than that in which you created it.
That problem persists even if I use a BackGroundWorker in the Form.
// This is a delegated on presenter when a File finish to upload
void client_FileUploadCompletedHandler(object sender, FileUploadCompletedEventArgs e)
{
string log = string.Format("{0} Upload from {1} to {2} is completed. Length: {3}. ",
DateTime.Now, e.LocalFile.FullName, e.ServerPath, e.LocalFile.Length);
archivosSubidos += 1;
_Publicacion.ProgresoSubida = (int)((archivosSubidos / archivosXSubir) * 100);
//this.lstLog.Items.Add(log);
//this.lstLog.SelectedIndex = this.lstLog.Items.Count - 1;
}
// This is My interfase
public interface IPublicacion
{
...
int ProgresoSubida { set; }
}
/// And Here is the implementartion of the interfase on the form
public partial class PublicarForm : Form ,IPublicacion
{
//Credenciales para conectarse al servicio FTP
public FTPClientManager client = null;
public XmlDocument conf = new XmlDocument();
public string workingDir = null;
public webTalk wt = new webTalk();
private readonly PublicacionesWebBL _Publicador;
public PublicarForm()
{
InitializeComponent();
String[] laPath = { System.AppDomain.CurrentDomain.BaseDirectory};
String lcPath = System.IO.Path.Combine(laPath);
_Publicador = new PublicacionesWebBL(this, lcPath);
}
public int ProgresoSubida
{
set
{
// This is my prograss bar, here it throw the exception.
prgProgresoSubido.Value = value;
}
}
}
How can I do to avoid this problem ?
In general, all updates to the User Interface and Controls has to be done from the main thread (event dispatcher). If you attempt to modify the properties of a control from a different thread you will get an exception.
You must call Control.Invoke to invoke on the event dispatcher the method that updates your UI
Control.Invoke
Here, place a button and a label on a form, then try this
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(TestThread));
t.Start();
}
private void TestThread()
{
for (int i = 0; i < 10; i++)
{
UpdateCounter(i);
Thread.Sleep(1000);
}
}
private void UpdateCounter(int i)
{
if (label1.InvokeRequired)
{
label1.Invoke(new ThreadStart(delegate { UpdateCounter(i); }));
}
else
{
label1.Text = i.ToString();
}
}
}
Realize, that if you are firing an event from a thread, that the event will be on the same Thread. Therefore, if that thread is not the event dispatcher, you'll need to invoke.
Also, there may be mechanisms that BackgroundWorker gives you (As the commentator said) that simplify this for you, but I've never used it before so I'll leave that up to you to investigate.
As Alan has just pointed out, you must do all operations with UI controls in UI thread.
Just modify your property like this:
public int ProgresoSubida
{
set
{
MethodInvoker invoker = delegate
{
prgProgresoSubido.Value = value;
}
if (this.InvokeRequired)
{
Invoke(invoker);
}
else
{
invoker();
}
}
}
I have a function that is called in rapid succession that has a open database connection.
my issue is that before one database connection is closed, another instance of the function is called and i could possibly receive a deadlock in the database.
I have tried:
private static WaitHandle[] waitHandles = new WaitHandle[]
{
new AutoResetEvent(false)
};
protected override void Broadcast(Data data, string updatedBy)
{
Action newAction = new Action(() =>
{
DataManagerFactory.PerformWithDataManager(
dataManager =>
{
// Update status and broadcast the changes
data.UpdateModifiedColumns(dataManager, updatedBy);
BroadcastManager.Instance().PerformBroadcast(
data,
BroadcastAction.Update,
Feature.None);
},
e => m_log.Error(ServerLog.ConfigIdlingRequestHandler_UpdateFailed() + e.Message));
}
);
Thread workerThread = new Thread(new ThreadStart(newAction));
ThreadPool.QueueUserWorkItem(workerThread.Start, waitHandles[0]);
WaitHandle.WaitAll(waitHandles);
}
but i recieve a thread error and the program freezes. It has something to do with the thread start function having no parameters i believe.
Thanks for any help
This is how it's done. Create class that does the job:
public class MyAsyncClass
{
public delegate void NotifyComplete(string message);
public event NotifyComplete NotifyCompleteEvent;
//Starts async thread...
public void Start()
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(DoSomeJob));
t.Start();
}
void DoSomeJob()
{
//just wait 5 sec for nothing special...
System.Threading.Thread.Sleep(5000);
if (NotifyCompleteEvent != null)
{
NotifyCompleteEvent("My job is completed!");
}
}
}
Now this is code from another class, that calls first one:
MyAsyncClass myClass = null;
private void button2_Click(object sender, EventArgs e)
{
myClass = new MyAsyncClass();
myClass.NotifyCompleteEvent += new MyAsyncClass.NotifyComplete(myClass_NotifyCompleteEvent);
//here I start the job inside working class...
myClass.Start();
}
//here my class is notified from working class when job is completed...
delegate void myClassDelegate(string message);
void myClass_NotifyCompleteEvent(string message)
{
if (this.InvokeRequired)
{
Delegate d = new myClassDelegate(myClass_NotifyCompleteEvent);
this.Invoke(d, new object[] { message });
}
else
{
MessageBox.Show(message);
}
}
Let me know if I need to explain some details.
Alternative to this is BackgroudWorker:
This question already has answers here:
WebBrowser Control in a new thread
(4 answers)
Closed 7 years ago.
I want to make 3 threads that each run the WebBroswer control. So I would like to use the ThreadPool to make things easy.
for(int i = 0;i < 3;i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(gotoWork), i));
}
WaitAll(waitHandles);
....../
void gotoWork(object o)
{
string url = String.Empty;
int num = (int)o;
switch(num)
{
case 0:
url = "google.com";
break;
case 1:
url = "yahoo.com";
break;
case 2:
url = "bing.com";
break;
}
WebBrowser w = new WebBrower();
w.Navigate(url);
}
But I get an error saying that I need a STA thread which the ThreadPool will never be. Before trying this method I tried this.
Thread[] threads = Thread[3];
for(int i = 0;i < 3;i++)
{
threads[i] = new Thread(new ParameterizedStart(gotoWork);
threads[i] = SetApartmentState(ApartmentState.STA); //whoo hoo
threads[i] = Start();
}
for(int i = 0; i < 3;i++)
{
threads[i].Join();
}
And the WebBrowsers all initialized and everything looks good but only one more two will actually do anything and its never consistant at all. Threading has been such a nightmare. Can anybody suggest a nice alternative?
public sealed class SiteHelper : Form
{
public WebBrowser mBrowser = new WebBrowser();
ManualResetEvent mStart;
public event CompletedCallback Completed;
public SiteHelper(ManualResetEvent start)
{
mBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(mBrowser_DocumentCompleted);
mStart = start;
}
void mBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Generated completed event
Completed(mBrowser);
}
public void Navigate(string url)
{
// Start navigating
this.BeginInvoke(new Action(() => mBrowser.Navigate(url)));
}
public void Terminate()
{
// Shutdown form and message loop
this.Invoke(new Action(() => this.Close()));
}
protected override void SetVisibleCore(bool value)
{
if (!IsHandleCreated)
{
// First-time init, create handle and wait for message pump to run
this.CreateHandle();
this.BeginInvoke(new Action(() => mStart.Set()));
}
// Keep form hidden
value = false;
base.SetVisibleCore(value);
}
}
An other class as
public abstract class SiteManager : IDisposable
{
private ManualResetEvent mStart;
private SiteHelper mSyncProvider;
public event CompletedCallback Completed;
public SiteManager()
{
// Start the thread, wait for it to initialize
mStart = new ManualResetEvent(false);
Thread t = new Thread(startPump);
t.SetApartmentState(ApartmentState.STA);
t.IsBackground = true;
t.Start();
mStart.WaitOne();
}
public void Dispose()
{
// Shutdown message loop and thread
mSyncProvider.Terminate();
}
public void Navigate(string url)
{
// Start navigating to a URL
mSyncProvider.Navigate(url);
}
public void mSyncProvider_Completed(WebBrowser wb)
{
// Navigation completed, raise event
CompletedCallback handler = Completed;
if (handler != null)
{
handler(wb);
}
}
private void startPump()
{
// Start the message loop
mSyncProvider = new SiteHelper(mStart);
mSyncProvider.Completed += mSyncProvider_Completed;
Application.Run(mSyncProvider);
}
}
class Tester :SiteManager
{
public Tester()
{
SiteEventArgs ar = new SiteEventArgs("MeSite");
base.Completed += new CompletedCallback(Tester_Completed);
}
void Tester_Completed(WebBrowser wb)
{
MessageBox.Show("Tester");
if( wb.DocumentTitle == "Hi")
base.mSyncProvider_Completed(wb);
}
//protected override void mSyncProvider_Completed(WebBrowser wb)
//{
// // MessageBox.Show("overload Tester");
// //base.mSyncProvider_Completed(wb, ar);
//}
}
On your main form:
private void button1_Click(object sender, EventArgs e)
{
//Tester pump = new Tester();
//pump.Completed += new CompletedCallback(pump_Completed);
//pump.Navigate("www.cnn.com");
Tester pump2 = new Tester();
pump2.Completed += new CompletedCallback(pump_Completed);
pump2.Navigate("www.google.com");
}
You need to host webbrowser control in somewhere to get it work (add it to a form), secondly you should use Invoke() of the host control (or a similar delegate) such as Form.Invoke() to interact with WebBrowser control.
No need to remind now but yes, your threads should be STA
You can use such type of class for your purpose to host WebBrowser control:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SomeNameSpace
{
public class WebForm : Form
{
public WebBrowser WebBrowser { get; set; }
public WebForm()
{
WebBrowser = new WebBrowser();
}
}
}
After all I choose this solution:
http://watin.sourceforge.net/documentation.html
In your case you should do this:
...
Thread thread = new Thread(SomeMethod);
thread.SetApartmentState(ApartmentState.STA);
...