|
Hi,
In my code I have interactions with a WPF control, so using Invoke I am able to call my functions, the problem I am having is that the code inside the function throws an exception, and I was wondering if it is possible to move the exception across the Invoke call. so that my code in the calling thread can handle it.
here is my code which hopefully shows the problem better:
<br />
public void SetProperty(String Path, String Value)<br />
{<br />
if (!this.Dispatcher.CheckAccess())<br />
{<br />
Exception exception = null;<br />
this.Dispatcher.Invoke((Action<String, String>)((path, val) => { <br />
<br />
try<br />
{<br />
SetProperty(path, val);
}<br />
catch (System.Exception e)<br />
{<br />
exception = e;<br />
}<br />
}), Path, Value, exception);<br />
if(exception != null){<br />
MessageBox.Show(exception.Message);<br />
}<br />
unfortunately this code doesn't work and I was wondering if there was a way around it.
Thank you in advance.
|
|
|
|
|
You could try putting the call to the Invoke in a try/catch and looking at the inner exception.
Not sure if it will work.
|
|
|
|
|
Thank you for the reply, I'm afraid that I have already tried that and it didn't work
|
|
|
|
|
At the top level, you can subscribe to AppDomain.CurrentDomain.UnhandledException , otherwise you pretty much have to catch the exception on the thread it was raised on AFAIK.
You can pass the exception by raising an event that takes an Exception as a parameter, then doing the updates to the UI via the subscribing method (remembering to do this on the Dispatcher Thread):
Action<Exception> ExceptionRaised;
public void SetProperty(String Path, String Value)
{
if (!this.Dispatcher.CheckAccess())
{
Exception exception = null;
this.Dispatcher.Invoke((Action<String, String>)((path, val) =>
{
try
{
SetProperty(path, val);
}
catch (System.Exception e)
{
exception = e;
}
}), Path, Value, exception);
}
public Constructor
{
ExceptionRaised += UpdateStatus;
}
void UpdateStatus(Exception exception)
{
if(exception == null)
return;
if (Thread.Current != Dispatcher.Current.Thread)
{
this.Dispatcher.Invoke(new Action<string>(UpdateStatus), new object[]{exception});
return;
}
MessageBox.Show(exception.Message);
}
Dalek Dave: There are many words that some find offensive, Homosexuality, Alcoholism, Religion, Visual Basic, Manchester United, Butter.
Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.
|
|
|
|
|
Hi,
I have a custom class CReadCDD where I intend to do some processing.
I placed the callbacks also inside this class (like mLoadXmlOnHeap_WorkThread).
From the Form class I instantiate my CReadCDD class and create the thread with call to mLoadXmlOnHeap_WorkThread.
In mLoadXmlOnHeap_WorkThread (not to have an additional proprty for the Form, I send an event to the Form class with the text I want as event args); the event is received in the Forms class, it goes to mfHandleCustomEvent_PrintRichTextConsole but here after entering
in Invoke method IT BLOCK my Form. The richtext control is not updated.
Where I did the mistake?
I read the MSDN but still I have problem to access the control from my thread
George
public class CReadCDD
{
private CProcessXMLdoc mdoc;
private string mFileName;
public RichTextBox pRichTextBox1 {get; set;}
public event EventHandler<CCustomEventArgs> RaiseCustomEvent;
protected void pOnRaiseCustomEvent(CCustomEventArgs pEv)
{
EventHandler<CCustomEventArgs> handler = RaiseCustomEvent;
if (handler != null)
handler(this, pEv);
}
public CReadCDD(string pFileName, Form1 pForm)
{
mFileName= pFileName;
}
#region Worker Threads
public void mLoadXmlOnHeap_WorkThread()
{
mdoc = new CProcessXMLdoc(mFileName);
CCustomEventArgs evObj= new CCustomEventArgs("Load The XML Data from Cdd file on the HEAP\n");
pOnRaiseCustomEvent(evObj);
}
}
namespace CddToCaplDiagnosticTestsGenerator
{
public partial class Form1 : Form
{
private CReadCDD objReadCdd;
public delegate void DelegateTypePrntText(string text);
public DelegateTypePrntText mdelT;
public Form1()
{
mdelT = new DelegateTypePrntText(mSetTextToRichTextControl);
InitializeComponent();
}
void mfHandleCustomEvent_PrintRichTextConsole(object sender, CCustomEventArgs e)
{
byte debug=0;
string text = e.pTextBox;
if (this.richTextBox1.InvokeRequired)
{
this.Invoke (mdelT, new object[] { text + " (Invoke)" });
}
else
richTextBox1.AppendText("No Invoke");
}
void mSetTextToRichTextControl(string pText)
{
richTextBox1.AppendText("Inner thread");
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "Cdd files (*.cdd)|*.cdd";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string filename = openFileDialog1.FileName;
try
{
objReadCdd= new CReadCDD(filename, this);
objReadCdd.RaiseCustomEvent += mfHandleCustomEvent_PrintRichTextConsole;
#region LoadXMLinMemory
objReadCdd.pRichTextBox1= richTextBox1;
Thread thrdLoadXmlOnHeap = new Thread(objReadCdd.mLoadXmlOnHeap_WorkThread);
thrdLoadXmlOnHeap.Start();
thrdLoadXmlOnHeap.Join();
#endregion
#region Load Data in the CData tree
#endregion
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
}
<
modified on Thursday, March 25, 2010 9:09 AM
|
|
|
|
|
After the first look I would say thrdLoadXmlOnHeap.Join(); is your problem.
After you started your thread from your main/guithread your main/guithread waits for the end of
the thread you started. This blocks your ui.
At first I would try just to comment this line out.
Greetings
Covean
|
|
|
|
|
|
You are welcome.
Greetings
Covean
|
|
|
|
|
hey,
I've a dictionary, which i sorted by value with linq, how can i get those sorted value from the sorted result i get
that's what i did so far
Dictionary<char, int> lettersAcurr = new Dictionary<char, int>();
var sortedDict = (from entry in lettersAcurr orderby entry.Value descending select entry);
during the debug i can see that sortedDic has a KeyValuePar, but i cant accesses to it
thanks for help
|
|
|
|
|
igalep132 wrote: but i cant accesses to it
What do you mean? You'll have to give a little more detail. What have you tried? Are there errors?
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
i meant that i don't know how to accesses to the sorted data
for example, i would like to iterate and print sorted data
i thought that sortedDic.GetEnumerator(), should help me here, but i was wrong...
|
|
|
|
|
foreach (KeyValuePair<char, int> kvp in sortedDic.Take(sortedDic.Count()))
Console.WriteLine(kvp.Value);
but it's to long, isn't it ?
|
|
|
|
|
Have you tried:
foreach (KeyValuePair<char, int> item in sortedDict)
{
}
Dalek Dave: There are many words that some find offensive, Homosexuality, Alcoholism, Religion, Visual Basic, Manchester United, Butter.
Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.
|
|
|
|
|
absolutely right...
i was looking for much complected solution
tanx ...
|
|
|
|
|
and if i want to iterate over specific numbers of values, and not over the whole KeyValuePair collection...
what should i do then ?
|
|
|
|
|
Ditcionaries are not intended for that sort of use, they are supposed to map a collection of [unique] keys to a value. As such they are unordered (there is a SortedDictionary type, but it sorts on key.
What you describe is a more like a list operation, as these have position. Iteraring over specific ranges depends upon what you really want to acheive:
1. You can use Linq to query out specific entries.
2. Dictionaries have a ToList() method, whose results you can iterate over.
3. The are both Keys and Values properties that can be iterated over.
Dalek Dave: There are many words that some find offensive, Homosexuality, Alcoholism, Religion, Visual Basic, Manchester United, Butter.
Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.
|
|
|
|
|
that's my solution
foreach (KeyValuePair<char, int> kvp in sortedDicByLetters)
{
if (i < 4)
{
encryptionKey[tmpCarr[i]] = kvp.Key;
i++;
}
else
break;
}
one more question,
after a sort a KeyValuePair with linq, how can i replace the old unsorted data inside the dictionary ?
tanks
|
|
|
|
|
HI,
Access Dictionary by using corresponding KeyValuePair
example use:
KeyValuePair<char, int> first = sortedDict.First<KeyValuePair<char, int>>();
Console.WriteLine("first element: " + first.Key + ": " + first.Value);
Console.WriteLine("all elements in order:");
foreach (KeyValuePair<char, int> pair in sortedDict)
{
Console.WriteLine(pair.Key+" : "+pair.Value);
}
|
|
|
|
|
Hi,
Just a basic question on delegates as I am unable to understand the exact use of it.
can anyone explain with a simple example what is the use of it?
Read that its being used to call functions at runtime?
- If we can call the methods of a class directly through its objects like obj.Method(), how do we achieve indirection using delegates.
- How can we achieve loose coupling or a communication between 2 classes through delegates.
Below is the sample code, i wrote in order to understand, but not able to.
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace DelegatesConsoleApp
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
11 A a = new A();
12 B b = new B();
13
14 MyDelegate[] del = new MyDelegate[3];
15 del[0] = new MyDelegate(a.MethodA);
16 del[1] = new MyDelegate(b.MethodB);
17 del[2] = new MyDelegate(CStatic.Method_CStatic);
18
19 del[0]();
20 Console.WriteLine();
21 del[1]();
22 Console.WriteLine();
23 del[2]();
24
25 Console.ReadKey();
26 }
27 }
28
29 delegate void MyDelegate();
30
31 class A
32 {
33
34 public A()
35 {
36 Console.WriteLine("Constructor of 'A' called");
37 }
38
39 public void MethodA()
40 {
41 Console.WriteLine("MethodA() of 'A' called");
42 }
43 }
44
45 class B
46 {
47 public B()
48 {
49 Console.WriteLine("Constructor of 'B' called");
50 }
51
52 public void MethodB()
53 {
54 Console.WriteLine("Method_B() of 'B' called");
55 }
56 }
57
58 class CStatic
59 {
60 public CStatic()
61 {
62 Console.WriteLine("Constructor of 'CStatic' called");
63 }
64
65 public static void Method_CStatic()
66 {
67 Console.WriteLine("Method_CStatic() of 'CStatic' called");
68 }
69 }
70 }
In above code, at lin # 15, 16, 17 we are assigning methods to the delegate, it means we need to create an object of class and call their methods. Why is the advantage of delegate of using delegate here as we can directly call the methods as we are passing it into delegate.
Thanks in advance.
Praveen Raghuvanshi
Software Engineer,
India.
|
|
|
|
|
In this case, you would have the advantage that you could call a method by index in the array del , without having to use verbose, slow and kludgy ways such as defining an interface for the method you want to call.
Of course, if you're not planning to use delegates for something useful and just directly calling them after you create them, there is just no point. But that's true for everything - you probably wouldn't write a function of method to add two integers, for example, but that doesn't mean that methods and functions are entirely useless.
Additionally, if you're working with delegates you could use anonymous methods, and there are no anonymous classes in C# as there are in Java, so if you were working purely with polymorphism instead of delegates or switch es you would have to define a whole new class for everything.
|
|
|
|
|
I'd read this:
http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx[^]
Especially the linked page "When to Use Delegates instead of interfaces".
Delegates are very useful, each time you subsribe to an event, delegates are used. The section on anonmous methods is interesting, as you then don't need an "actual" method. The are also used under the hood a lot in LINQ, so for example:
List<MyType> list = new List<MyType>();
list.Sort((x,y) => x.AString.Compare(y.AString):
The Labmda being used is really an anonymous delegate.
Also Action and Action<T> are worth looking up, they prevent a lot of needless delegate declarations
Dalek Dave: There are many words that some find offensive, Homosexuality, Alcoholism, Religion, Visual Basic, Manchester United, Butter.
Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.
modified on Thursday, March 25, 2010 7:56 AM
|
|
|
|
|
Keith Barrow wrote: Action and Action
What's the difference
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
I think your angle brackets have been swallowed!
List<T> and one of the Actions should read Action<T>
DaveIf this helped, please vote & accept answer!
Binging is like googling, it just feels dirtier. (Pete O'Hanlon)
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
|
|
|
|
|
+ @Mark
Fixed!
Dalek Dave: There are many words that some find offensive, Homosexuality, Alcoholism, Religion, Visual Basic, Manchester United, Butter.
Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.
|
|
|
|
|
Hei,
Is there any way by which we can design culture dependent Crystal Reports. e.g. For German language all the captions inside the crystal report converted in to german language and so as french.
Thanks
Syed Shahid Hussain
|
|
|
|
|