Alw1n
asked on
Threadpool arguments have strange values
Hi,
I cannot figure out what I am doing wrong in my code below, I would expect a print of "1" then "2" but instead I get "3" and "3", please help.
private void bTest_Click(object sender, EventArgs e)
{
for (int i = 1; i <= 2; i++)
{
XX xx = new XX();
ThreadPool.QueueUserWorkIt em(o =>
{
try
{
xx.SendMsg(i);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message );
}
});
}
}
public class XX
{
public void SendMsg(object n)
{
System.Diagnostics.Debug.P rint( n.ToString());
}
}
I cannot figure out what I am doing wrong in my code below, I would expect a print of "1" then "2" but instead I get "3" and "3", please help.
private void bTest_Click(object sender, EventArgs e)
{
for (int i = 1; i <= 2; i++)
{
XX xx = new XX();
ThreadPool.QueueUserWorkIt
{
try
{
xx.SendMsg(i);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message
}
});
}
}
public class XX
{
public void SendMsg(object n)
{
System.Diagnostics.Debug.P
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You can use try/catch within a regular function as well--you just don't see them until you actually navigate to that function (within the IDE). If there is a benefit to using one over the other, I don't know what it would be. To me it seems a matter of preference. Either way you are passing a function.
ASKER
ThreadPool.QueueUserWorkIt
The only benefit I see to using lambda is that you can use try/catch blocks etc. around the call, would there be any other reason to use lambda vs the original way?