我已经做了很多尝试,但我无法找到如何更新GUI元素,例如,在上运行任务的TextBlock.Text。
有办法这样做吗?
它应该在没有停止的情况下完成正在运行的任务。
根据我的回答,我尝试过这样做:
Task t1 = new Task(() =>
{
while (1 == 1)
{
byte[] writeBuffer = { 0x41, 0x01, 0 }; // Buffer to write to mcp23017
byte[] readBuffer = new byte[3]; // Buffer to read to mcp23017
SpiDisplay.TransferFullDuplex(writeBuffer, readBuffer); // Send writeBuffer to mcp23017 and receive Results to readBuffer
byte readBuffer2 = readBuffer[2]; // extract the correct result
string output = Convert.ToString(readBuffer2, 2).PadLeft(8, '0'); // convert result to output Format
// Update the frontend TextBlock status5 with result
Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
// Your UI update code goes here!
status6.Text = output;
});
}
});
t1.Start(); 但我得到以下两个错误:
Error CS0103 The name 'CoreDispatcherPriority' does not exist in the current context和
CS4014 Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.我是不是用代码做错了什么?
发布于 2015-08-03 09:50:29
我不知道你的问题在哪里,我想可能是不同线程的问题。试着用调度员。您需要集成Windows.UI.Core命名空间:
using Windows.UI.Core;这是您的电话(稍微修改一下,以便开箱即用)。
private void DoIt()
{
Task t1 = new Task(async () =>
{
while (1 == 1)
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
// Your UI update code goes here!
status6.Text = "Hello" + DateTime.Now;
});
await Task.Delay(1000);
}
});
t1.Start();
} 小提示:虽然(1=1)听起来像是一个无限循环。另一个提示:我添加了“等待Task.Delay(1000)”,以便在循环期间有一个小中断。
也请查看这个关于调度器的答案。Correct way to get the CoreDispatcher in a Windows Store app
https://stackoverflow.com/questions/31783242
复制相似问题