Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Task Async Await Silverlight 5 Cross-Thread Violation

Posted on 2013-01-29
6
Medium Priority
?
1,144 Views
Last Modified: 2013-03-31
Hi,
I'm trying to use the TPL in my SL5 application to simplify the Async Service calls.

I'm calling the following from my MainPage code behind, with the method being called being an async void that does the work with the service proxy. An Cross-Thread access exception always gets thrown for this code, and none of the asyn void code is reached, even though I'm not trying to interact with the UI:

var result = Task.Factory.StartNew(WCFServiceQueryHelper.StoreData);
                        await result;

Open in new window


Am I missing something, or is there a better way to perform this. Basically I need to use this static method (WCFServiceQueryHelper.StoreData), wait for it to complete, without blocking the UI thread, then continue to the next method after handling any exception caught.

This is to replace all the direct service calls, and callback events in the mainpage code, as it gets very messy. The static method (WCFServiceHelper) will use async/await and interact with the ServiceProxy, meaning the MainPage code can simply call this static method, and when complete, move onto the next method.

Thanks
0
Comment
Question by:wint100
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
6 Comments
 
LVL 25

Expert Comment

by:apeter
ID: 38837599
Can we see the complete method, "WCFServiceQueryHelper.StoreData". Looks like this method is blocking or doing something...

Just to test,  if you just have "return statement" in above method, does your code works fine ?
0
 
LVL 1

Author Comment

by:wint100
ID: 38838605
Hi,

Thanks for your feedback. Methods called are below. changing the method to return gives the same exception:

{System.UnauthorizedAccessException: Invalid cross-thread access.
   at MS.Internal.XcpImports.CheckThread()
   at System.Windows.Application.get_Host()
   at EnergyViewerV2.Helpers.ElecWCFServiceQueryHelper..cctor()}

public static async void StoreElecAnnualData()
        {
            //Annual Electric Data Collection

            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                if (app.ElecAnnualData == null)
                {
                    if (DeserializeAnnualDataFromXML("ElecAnnual" + app.ObjRefs[app.CurrentBuilding].BuildingNo + app.ObjRefs[app.CurrentBuilding].BuildingName) != null) app.ElecAnnualData = DeserializeAnnualDataFromXML("ElecAnnual" + app.ObjRefs[app.CurrentBuilding].BuildingNo + app.ObjRefs[app.CurrentBuilding].BuildingName);
                }
                if (app.ElecPrevAnnualData == null)
                {
                    if (DeserializeAnnualDataFromXML("ElecPrevAnnual" + app.ObjRefs[app.CurrentBuilding].BuildingNo + app.ObjRefs[app.CurrentBuilding].BuildingName) != null) app.ElecPrevAnnualData = DeserializeAnnualDataFromXML("ElecPrevAnnual" + app.ObjRefs[app.CurrentBuilding].BuildingNo + app.ObjRefs[app.CurrentBuilding].BuildingName);
                }
            }
            else
            {
                try
                {
                    sDate = app.isRollingAnnual?RollingDatesHelper.AnnualCurrentPeriodStart().ToLongDateString(): DateTime.Now.ToLongDateString();

                    app.ElecAnnualData = await ServiceProxy.GetAnnualData(sDate,
                                                                          app.isRollingAnnual
                                                                              ? RollingDatesHelper.
                                                                                    AnnualCurrentPeriodEnd().
                                                                                    ToLongDateString()
                                                                              : null,
                                                                          app.ObjRefs[app.CurrentBuilding].elecMeter,
                                                                          app.isRollingAnnual ? 7000 : 3000, false,
                                                                          false);

                    //Store the data to IS
                    if (app.ElecAnnualData != null) SerializeAnnualDataListToXML(app.ElecAnnualData, "ElecAnnual" + app.ObjRefs[app.CurrentBuilding].BuildingNo + app.ObjRefs[app.CurrentBuilding].BuildingName);
                    
                    sDate2 = app.isRollingAnnual ? RollingDatesHelper.AnnualPreviousPeriodStart().ToShortDateString() : DateTime.Now.AddMonths(-12).ToShortDateString();
                    app.ElecPrevAnnualData =
                        await
                        ServiceProxy.GetAnnualData(sDate2,
                                                   app.isRollingAnnual
                                                       ? RollingDatesHelper.AnnualPreviousPeriodEnd().ToShortDateString()
                                                       : null, app.ObjRefs[app.CurrentBuilding].elecMeter,
                                                   app.isRollingAnnual ? 8000 : 4000, false, false);
                     

                    //Store the data to IS
                    if (app.ElecPrevAnnualData != null) SerializeAnnualDataListToXML(app.ElecPrevAnnualData, "ElecPrevAnnual" + app.ObjRefs[app.CurrentBuilding].BuildingNo + app.ObjRefs[app.CurrentBuilding].BuildingName);


                }
                catch (Exception ex)
                {
                    errorHandling.Error("The following error occurred trying to gather Annual Elec Data from Database: " + ex.Message, "Annual Elec Error", app.isDebugging);
                
                    if (app.ElecAnnualData == null)
                    {
                        if (DeserializeAnnualDataFromXML("ElecAnnual" + app.ObjRefs[app.CurrentBuilding].BuildingNo + app.ObjRefs[app.CurrentBuilding].BuildingName) != null) app.ElecAnnualData = DeserializeAnnualDataFromXML("ElecAnnual" + app.ObjRefs[app.CurrentBuilding].BuildingNo + app.ObjRefs[app.CurrentBuilding].BuildingName);
                    }
                    if (app.ElecPrevAnnualData == null)
                    {
                        if (DeserializeAnnualDataFromXML("ElecPrevAnnual" + app.ObjRefs[app.CurrentBuilding].BuildingNo + app.ObjRefs[app.CurrentBuilding].BuildingName) != null) app.ElecPrevAnnualData = DeserializeAnnualDataFromXML("ElecPrevAnnual" + app.ObjRefs[app.CurrentBuilding].BuildingNo + app.ObjRefs[app.CurrentBuilding].BuildingName);
                    }


                }
            }




        }

Open in new window


With the ServiceProxy class as follows:

public class ServiceProxy
    {
        static Uri address = new Uri(Application.Current.Host.Source, "../Services/SilverlightService.svc");

        public static Task<ObservableCollection<EnergyData>> GetAnnualData(string sDate, string eDate, string MeterID, int index,
                                              bool occupancyRequired, bool tempRequired)
        {
            var tcs = new TaskCompletionSource<ObservableCollection<EnergyData>>();

            var client = new SilverlightServiceClient("CustomBinding_SilverlightService", address.AbsoluteUri);

            client.getAnnualDataCompleted += (s, e) =>
            {
                if (e.Error != null)
                    tcs.TrySetException(e.Error);
                else if (e.Cancelled)
                    tcs.TrySetCanceled();
                else
                    tcs.TrySetResult(e.Result);
            };

            client.getAnnualDataAsync(sDate,eDate,MeterID,index,occupancyRequired,tempRequired);

            return tcs.Task;
        }

    }

Open in new window

0
 
LVL 1

Author Comment

by:wint100
ID: 38841083
Checking though my code, it looks like I'm calling the first method within a new Threadpool.QueueUserWorkItem:

ThreadPool.QueueUserWorkItem(delegate
                                                   {

CallMethod();
};
0
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 
LVL 25

Expert Comment

by:apeter
ID: 38847627
From the code, it doesn't looks like accessing any UI element.   Did you tried to call debug and fine which line the error is thrown? Maybe a test method which call just the above method.
0
 
LVL 1

Accepted Solution

by:
wint100 earned 0 total points
ID: 38848423
I removed the Threadpool code and the problem went away. It must have been firing in a different thread due to the threadpool.

Thanks
0
 
LVL 1

Author Closing Comment

by:wint100
ID: 39035175
Found the solution
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For most people, the WrapPanel seems like a magic when they switch from WinForms to WPF. Most of us will think that the code that is used to write a control like that would be difficult. However, most of the work is done by the WPF engine, and the W…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question