I'm working on a WinRT component in C# which I'm calling from WinJS asyncronously.
I'm calling a library which when called, throws The application called an interface that was marshalled for a different thread
exception. I understand this to be an issue with the thread that the library code is running on, via the UI thread the JS code is running under.
I've found some threads on here which mention ways this can potentially work ( Run code on UI thread in WinRT etc ) but none of these touch on calling code from WinJS, they all tend to be XAML.
So, I'm hoping to answer two questions:
- At a high level, should I by trying to make the WinRT library code run on the UI thread? thereby making it syncronous? if that is correct, what is the most effective way to make my WinRT code which handles writing to the file system, behave in this way (code below)
RT Code
public IAsyncOperation<string> ButtonPress()
{
return SaveSpreadsheet().AsAsyncOperation();
}
private async Task<string> SaveSpreadsheet()
{
var res = false;
try
{
CreateSpreadsheet();
AddSomeContentToASheet();
var folder = KnownFolders.DocumentsLibrary;
var outFile = await folder.CreateFileAsync("New.xls", CreationCollisionOption.ReplaceExisting);
res = await book.SaveAsAsync(outFile, ExcelSaveType.SaveAsXLS);
book.Close();
engine.Dispose();
}
catch (Exception e)
{
return e.Message;
}
return "Success! " + res;
}
JS Code
button.onclick = function () {
var rtComponent = new WindowsRuntimeComponent1.Class1();
rtComponent.buttonPress().then(function (res) {
document.getElementById('res').innerText = "Export should have: " + res;
});
};
- If 1 is wrong and I should by trying to leave the RT code async but running on the same thread as my JS UI code, how can I get a reference to that thread, and then kick off the methods in the RT code? I've tried some
Dispatcher.RunAsync()
ways of running the RT code, but I come unstuck when I need to get a reference to anIStorageFile
through the WinRT framework methods.
Any thoughts greatly appreciated.