Pass Parameter or Arguments to a Background task in Uwp

扶醉桌前 提交于 2019-12-07 04:14:02

问题


I am creating a uwp app in which I want to take some data from user say from a textbox and then pass it to a background task. But when I am trying to add project reference to the background task I am getting a circular reference error. So is there any way to pass arguments maybe a overload of run function or anything else. Thanks in advance.


回答1:


Romasz has explained it perfectly but in your case you can get the user data from the textbox by doing these steps:

1.Declare this in MainPage.xaml.cs(or your xaml page)

var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["user"] = User.Text;

2.Now get the data in BackgroundTask.cs using these

var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
string user = localSettings.Values["user"].ToString();

Here the variable user has the texbox data you wanted from the mainpage.

Note:I have assumed that you have named your textbox "User"




回答2:


There is no direct way to do what you want, each process (for example BTask and UI) has its own memory and it cannot be accessed just like that.

You will need some kind of a broker for this purpose - for short communication I think you can use LocalSettings, which should work fine - though in case of complex objects you may need to serialize them first. For more advanced communication you may also think of using a file in LocalFolder or other place that is accessible for all processes.

In some cases there may be a problem of synchronization of processes (or accessing shared resources, like files) - for this, there are designed objects for global synchronization, eg. Mutex, EventWaitHanle.



来源:https://stackoverflow.com/questions/40523558/pass-parameter-or-arguments-to-a-background-task-in-uwp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!