How to integrate threading with a www query for a UWP app?
I am new to threading in C#, so I appreciate any help! I have been using a coroutine to get a JSON packet from the web once a second, then parse it into a JSON object, and then send that information (using Zenject signals) to another method to trigger processing, but I'm finding that because this is on the main thread it is holding up the rest of the processing. This is more or less what I currently have:
void Start()
{
StartCoroutine(query());
}
IEnumerator query()
{
while (true)
{
WWW www = new WWW("website.com");
yield return www;
string text = www.text;
MyObject obj = JsonUtility.FromJson<MyObject>(text);
_signal.Fire(obj);
yield return new WaitForSeconds(1);
}
}
I'm wondering, how can I move this to run on a separate thread? This link suggests on its point #4 to use Mono's ThreadPool, but notes that you have to use the #if UNITY_EDITOR when building for a UWP app. I've tried ThreadPool.QueueUserWorkItem(query), but that is not compatible with a coroutine, and I'm not sure how to convert my coroutine to a method since I need to wait for the website's return. I looked into using UniRx but was having a really hard time understanding the documentation. I tried implementing with it:
void Start()
{
var query = Observable.Start(() =>
{
string x;
while (true)
{
ObservableWWW.Get("website.com").Subscribe(x => text = x);
MyObject obj = JsonUtility.FromJson<MyObject>(text);
_signal.Fire(obj);
yield return new WaitForSeconds(1);
}
}
}
However, this doesn't seem to run at all. I would appreciate any help or advice on how to turn this into a separate thread!
I also just tried using:
void Start()
{
#if UNITY_EDITOR
Thread queryThread = new System.Threading.Thread(() =>
{
while(true)
{
query();
System.Threading.Thread.Sleep(1000);
}
});
queryThread.Start();
#endif
}
void query()
{
WWW www = new WWW("website.com");
yield return www;
string text = www.text;
$$anonymous$$yObject obj = JsonUtility.FromJson<$$anonymous$$yObject>(text);
_signal.Fire(obj);
}
but I'm getting Unity init WWW can only be called on the main thread. So, I tried replacing
WWW www = new WWW("website.com");
yield return www;
with:
ObservableWWW.Get("website.com").Subscribe(x => text = x);
but I'm now getting enforceWebSecurityRestrictions can only be called from the main thread. That is a call from within the UniRx. I'd still appreciate any help!
This site seems like it had a neat potential answer with this code:
class TestAsync : $$anonymous$$onobehaviour
{
void Start()
{
DoTaskAsync();
}
public async void DoTaskAsync()
{
await Task.Run(()=>
{
//a long-running operation...
});
}
}
but when I try to make a method async, I get the error within Visual Studio 'Feature async function is not available in C# 4. Please use language version 5 or greater'
I'm assu$$anonymous$$g this is a restriction of Unity? Although their example uses a monobehaviour.... I am using Unity 5.6 by the way.