使用TheadPool以及CoreDispatcher可以实现使用工作线程与更新UI的功能。
其中CoreDispatcher应当在UI线程中获取,并在工作线程的callback函数中使用;否则CoreDispatcher是获取不到的。
不过win8中建议是使用Task来代替TheadPool,因为它提供了一些比较实用的接口,例如取消工作线程中的任务等。
using System;
using System.Collections.Generic;
using System.IO;
using Windows.UI.Xaml;
using Windows.System.Threading;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.Foundation;
// 封装了HttpPostRequest
using MyProject.HttpPost;
namespace HttpTest
{
/// <summary>
/// 管理用户登陆退出
/// </summary>
public class AccountServer
{
// 用于调起UI线程
private Window m_CurWindow;
private CoreDispatcher m_CurCoreDispatcher;
// 登陆操作处理完成
public EventHandler<LoginCompletedEventArgs> LoginCompleted;
#region Constructor
public AccountServer()
{
m_CurWindow = Window.Current;
}
#endregion
#region Public Methods
/// <summary>
/// 用户登陆
/// </summary>
/// <param name="userName">用户名</param>
/// <param name="pwd">用户密码</param>
public void Login(string userName, string pwd)
{
m_CurCoreDispatcher = m_CurWindow.Dispatcher;
ThreadPool.RunAsync(AsyncRequestLogin);
}
#region Private Methods
private HttpPostRequest HttpPostRequestInstance
{
get
{
if (null == m_HttpPostRequest)
{
m_HttpPostRequest = new HttpPostRequest();
}
return m_HttpPostRequest;
}
}
private void AsyncRequestLogin(object state)
{
HttpPostRequestInstance.AsyncRequest(LoginUrl, HttpPostParam.PrepareLoginParams(m_UserName, m_Pwd), AsyncLoginCallback);
}
private void AsyncLoginCallback(string msg)
{
if (string.Empty == msg)
{
NotifyLoginCompletedEvent(new LoginCompletedEventArgs(false,false));
}
else
{
HttpPostResult res = new HttpPostResult(msg);
long error = res.GetErrorCode();
if (error == HttpPostResult.NoneError)
{
Account account = res.GetAccount();
account.IsLogging = true;
account.Password = m_Pwd;
NotifyLoginCompletedEvent(new LoginCompletedEventArgs(true, account));
}
else
{
NotifyLoginCompletedEvent(new LoginCompletedEventArgs(false));
}
}
}
private void NotifyLoginCompletedEvent(LoginCompletedEventArgs args)
{
m_CurCoreDispatcher.RunAsync(CoreDispatcherPriority.High,() =>
{
if (LoginCompleted != null)
LoginCompleted(this, args);
});
}
#endregion
}
}